Example usage for java.io File createTempFile

List of usage examples for java.io File createTempFile

Introduction

In this page you can find the example usage for java.io File createTempFile.

Prototype

public static File createTempFile(String prefix, String suffix, File directory) throws IOException 

Source Link

Document

Creates a new empty file in the specified directory, using the given prefix and suffix strings to generate its name.

Usage

From source file:ZipSourceCallable.java

@Override
public String invoke(File f, VirtualChannel channel) throws IOException {
    String sourceFilePath = workspace.getRemote();

    // Create a temp file to zip into so we do not zip ourselves
    File tempFile = File.createTempFile(f.getName(), null, null);
    try (OutputStream zipFileOutputStream = new FileOutputStream(tempFile)) {
        try (ZipOutputStream out = new ZipOutputStream(zipFileOutputStream)) {
            zipSource(workspace, sourceFilePath, out, sourceFilePath);
        }//from  w ww .  j a  v  a  2s . co  m
    } catch (IOException e) {
        throw e;
    } catch (Exception e) {
        throw new IOException(e);
    }

    // Copy zip to the location we expect it to be in
    FileUtils.copyFile(tempFile, f);

    try {
        tempFile.delete();
    } catch (Exception e) {
        // If this fails, the file will just be cleaned up
        // by the system later.  We are just trying to be
        // good citizens here.
    }

    String zipFileMD5;

    // Build MD5 checksum before returning
    try (InputStream zipFileInputStream = new FileInputStream(f)) {
        zipFileMD5 = new String(encodeBase64(DigestUtils.md5(zipFileInputStream)), Charsets.UTF_8);
        return zipFileMD5;
    }
}

From source file:com.barchart.udt.TestSocketFile.java

/**
 * verify basic file send/receive//w  ww. ja v a2  s .  c  o  m
 */
@Test(timeout = 10 * 1000)
public void fileTransfer() throws Exception {

    final InetSocketAddress addr1 = localSocketAddress();
    final InetSocketAddress addr2 = localSocketAddress();

    final SocketUDT peer1 = new SocketUDT(TypeUDT.STREAM);
    final SocketUDT peer2 = new SocketUDT(TypeUDT.STREAM);

    peer1.setBlocking(false);
    peer2.setBlocking(false);

    peer1.setRendezvous(true);
    peer2.setRendezvous(true);

    peer1.bind(addr1);
    peer2.bind(addr2);

    socketAwait(peer1, StatusUDT.OPENED);
    socketAwait(peer2, StatusUDT.OPENED);

    peer1.connect(addr2);
    peer2.connect(addr1);

    socketAwait(peer1, StatusUDT.CONNECTED);
    socketAwait(peer2, StatusUDT.CONNECTED);

    log.info("state 0 - connected");
    log.info("peer1 : {}", peer1);
    log.info("peer2 : {}", peer2);

    final int size = 64 * 1024;

    final Random random = new Random(0);
    final byte[] array1 = new byte[size];
    final byte[] array2 = new byte[size];
    random.nextBytes(array1);
    random.nextBytes(array2);

    final File folder = new File("./target/file");
    folder.mkdirs();

    final File source = File.createTempFile("source", "data", folder);
    final File target = File.createTempFile("target", "data", folder);

    FileUtils.writeByteArrayToFile(source, array1);
    FileUtils.writeByteArrayToFile(target, array2);

    assertEquals(size, source.length());
    assertEquals(size, target.length());

    assertFalse("files are different", FileUtils.contentEquals(source, target));

    // sender
    final Runnable task1 = new Runnable() {
        @Override
        public void run() {
            try {
                log.info("init send");
                final long length = peer1.sendFile(source, 0, size);
                assertEquals(length, size);
            } catch (final Exception e) {
                log.error("", e);
            }
        }
    };

    // receiver
    final Runnable task2 = new Runnable() {
        @Override
        public void run() {
            try {
                log.info("init recv");
                final long length = peer2.receiveFile(target, 0, size);
                assertEquals(length, size);
            } catch (final Exception e) {
                log.error("", e);
            }
        }
    };

    final ExecutorService executor = Executors.newFixedThreadPool(2);

    executor.submit(task1);
    executor.submit(task2);

    Thread.sleep(5 * 1000);

    executor.shutdownNow();

    assertTrue("files are the same", FileUtils.contentEquals(source, target));

    peer1.close();
    peer2.close();

}

From source file:com.microsoft.tfs.core.util.internal.AppleSingleUtil.java

/**
 * Encodes a file in-place, creating an AppleSingle file in place of the
 * given file./*w  ww .  j  a  va  2  s . com*/
 *
 * Technically creates an AppleSingle file in a temp file and renames it
 * over the given file. Note that this is not atomic.
 *
 * @param file
 *        The file to encode into an AppleSingle file
 * @param filename
 *        The output filename to encode in the AppleSingle file
 */
public static void encodeFile(final File file, final String filename) throws IOException {
    /*
     * Do not alter files on non-Mac OS X platforms
     *
     * TODO: at some point we should split these into data fork +
     * AppleDouble files
     */
    if (!Platform.isCurrentPlatform(Platform.MAC_OS_X)) {
        throw new IOException(
                MessageFormat.format(Messages.getString("AppleSingleUtil.NotSupportedOnPlatformFormat"), //$NON-NLS-1$
                        Platform.getCurrentPlatformString()));
    }

    final File directory = file.getParentFile();
    File temp = File.createTempFile("teApple", ".tmp", directory); //$NON-NLS-1$ //$NON-NLS-2$

    try {
        AppleSingleEncoderStream input = null;
        OutputStream output = null;

        /*
         * Create an AppleSingleEncoderStream. This is what does all the
         * magic, it reads a file and its resource forks, metadata, etc, off
         * disk and provides that information in an AppleSingle stream.
         *
         * Note that we allow callers to override filename (as they're
         * usually giving us a temp file) and we use an epoch date (to
         * ensure md5 sanity on unchanged files.)
         */
        try {
            input = new AppleSingleEncoderStream(file);
            input.setFilesystem("Teamprise"); //$NON-NLS-1$
            input.setFilename(filename);
            input.setDate(new Date(0));

            output = new FileOutputStream(temp);

            duplicateFile(input, output);
        } finally {
            if (input != null) {
                try {
                    input.close();
                } catch (final Exception e) {
                    log.warn(Messages.getString("AppleSingleUtil.CouldNotCloseAppleSingleInputStream"), e); //$NON-NLS-1$
                }
            }

            if (output != null) {
                try {
                    output.close();
                } catch (final Exception e) {
                    log.warn(Messages.getString("AppleSingleUtil.CouldNotCloseAppleSingleOutputStream"), e); //$NON-NLS-1$
                }
            }
        }

        renameFile(temp, file);
        temp = null;
    } finally {
        if (temp != null) {
            temp.delete();
        }
    }
}

From source file:com.moz.fiji.schema.tools.TestCreateTableTool.java

private File createTempTextFile(final String content) throws IOException {
    final File file = File.createTempFile("temp-", ".txt", getLocalTempDir());
    final OutputStream fos = new FileOutputStream(file);
    try {/*  ww w.j  a v a  2 s.  c o m*/
        IOUtils.write(content, fos);
    } finally {
        fos.close();
    }
    return file;
}

From source file:controller.UpdateImage.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    PrintWriter out = response.getWriter();
    HttpSession session = request.getSession();
    String manv = session.getAttribute("manv").toString();
    if (!ServletFileUpload.isMultipartContent(request)) {
        out.println("Nothing to upload");
        return;/* w  ww  .j av a2 s .c om*/
    }
    FileItemFactory itemfactory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(itemfactory);
    String a = "";
    try {
        List<FileItem> items = upload.parseRequest(request);
        for (FileItem item : items) {
            String myfolder = ("asset/Images/nhanvien") + "/";
            File uploadDir = new File(
                    "E:/Cng ngh phn m?m/? ?n/1996Shop/ShopOnline/web/asset/Images/nhanvien");
            File file = File.createTempFile("img", ".png", uploadDir);
            item.write(file);
            a = myfolder + file.getName();
            nv.setImage(a);
            usersDAO.updateImage(a, manv);
            response.sendRedirect("Profile.jsp?MaNV=" + manv + "");
        }

    } catch (FileUploadException e) {
        out.println("upload fail");
    } catch (Exception ex) {

    }
}

From source file:org.pau.assetmanager.viewmodel.chart.ResourceImageGenerator.java

@Override
public String apply(JFreeChart jfchart) {
    String tempFileName = "";
    try {/*  w w  w. j a v  a  2s .c  o m*/
        ServletContext servletContext = Sessions.getCurrent().getWebApp().getServletContext();
        String tempDirPath = servletContext.getRealPath("") + File.separator + "TMP";
        File tempDir = new File(tempDirPath);
        if (!tempDir.exists()) {
            tempDir.mkdir();
        } else {
            cleanTempFolder(tempDir);
        }
        File tempFile = File.createTempFile("tmp", ".png", tempDir);
        tempFileName = tempFile.getName();
        FileOutputStream fileOutputStream = new FileOutputStream(tempFile);
        ChartUtilities.writeChartAsPNG(fileOutputStream, jfchart, 1200, 500);
    } catch (Throwable t) {
        logger.error("Error generating chart.", t);
    }
    Clients.clearBusy();
    return "TMP" + File.separator + tempFileName;
}

From source file:$.FileUtils.java

/**
     * Get temporary file// w  w w. j a  v a  2 s.co m
     * @param name File name
     * @param suffix Suffix
     * @return Temp file folder
     */
    public static File getTmpFile(final String name, final String suffix) {
        String suffixToUse = suffix == null ? ".tmp" : suffix;
        if (!suffixToUse.startsWith(".")) {
            suffixToUse = "." + suffix;
        }
        String nameToUse = name == null ? "tmp" : name;
        File input = null;
        try {
            File folder = new File(JAVA_TMP, FileUtils.TMP_DIR);
            if (!folder.exists()) {
                boolean mkdirs = folder.mkdirs();
                checkCreation(folder, mkdirs);
            }
            input = File.createTempFile(nameToUse, suffixToUse, folder);
            input.deleteOnExit();
        } catch (IOException e) {
            logger.error("An error occurred while creating the temporary file: \"" + name + suffix + "\"");
        }
        return input;
    }

From source file:com.portalbook.charting.PortletUtilities.java

/**
 * Saves the chart as a PNG format file in the temporary directory and
 * populates the ChartRenderingInfo object which can be used to generate
 * an HTML image map./*ww w.ja  v a  2 s  .  c o  m*/
 *
 * @param chart  the chart to be saved (<code>null</code> not permitted).
 * @param width  the width of the chart.
 * @param height  the height of the chart.
 * @param info  the ChartRenderingInfo object to be populated (<code>null</code> permitted).
 * @param session  the PortletSession of the client.
 *
 * @return the filename of the chart saved in the temporary directory.
 *
 * @throws IOException if there is a problem saving the file.
 */
public static String saveChartAsPNG(JFreeChart chart, int width, int height, ChartRenderingInfo info,
        PortletSession session) throws IOException {
    if (chart == null) {
        throw new IllegalArgumentException("Null 'chart' argument.");
    }
    ServletUtilities.createTempDir();
    File tempFile = File.createTempFile(PortletUtilities.getTempFilePrefix(), ".png",
            new File(System.getProperty("java.io.tmpdir")));
    ChartUtilities.saveChartAsPNG(tempFile, chart, width, height, info);
    PortletUtilities.registerChartForDeletion(tempFile, session);
    return tempFile.getName();
}

From source file:edu.cmu.cs.diamond.android.Filter.java

public Filter(int resourceId, Context context, String name, String[] args, byte[] blob) throws IOException {
    Resources r = context.getResources();
    String resourceName = r.getResourceEntryName(resourceId);
    File f = context.getFileStreamPath(resourceName);

    if (!f.exists()) {
        InputStream ins = r.openRawResource(resourceId);
        byte[] buf = IOUtils.toByteArray(ins);
        FileOutputStream fos = context.openFileOutput(resourceName, Context.MODE_PRIVATE);
        IOUtils.write(buf, fos);/*from  www  . j a v a2  s  . c  o m*/
        context.getFileStreamPath(resourceName).setExecutable(true);
        fos.close();
    }

    ProcessBuilder pb = new ProcessBuilder(f.getAbsolutePath());
    Map<String, String> env = pb.environment();
    tempDir = File.createTempFile("filter", null, context.getCacheDir());
    tempDir.delete(); // Delete file and create directory.
    if (!tempDir.mkdir()) {
        throw new IOException("Unable to create temporary directory.");
    }
    env.put("TEMP", tempDir.getAbsolutePath());
    env.put("TMPDIR", tempDir.getAbsolutePath());
    proc = pb.start();
    is = proc.getInputStream();
    os = proc.getOutputStream();

    sendInt(1);
    sendString(name);
    sendStringArray(args);
    sendBinary(blob);

    while (this.getNextToken().tag != TagEnum.INIT)
        ;
    Log.d(TAG, "Filter initialized.");
}

From source file:info.magnolia.ui.form.field.upload.DefaultFileFactory.java

@Override
public File createFile(String fileName, String mimeType) {
    try {//from  w  w w  . ja v  a2  s.com
        File tmpFile = File.createTempFile(StringUtils.rightPad(fileName, 5, "x"), null, directory);
        tmpFile.deleteOnExit();
        return tmpFile;
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}