Example usage for java.io File deleteOnExit

List of usage examples for java.io File deleteOnExit

Introduction

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

Prototype

public void deleteOnExit() 

Source Link

Document

Requests that the file or directory denoted by this abstract pathname be deleted when the virtual machine terminates.

Usage

From source file:com.github.pitzcarraldo.openjpeg.OpenJPEGLoader.java

private static void copyStreamToFile(InputStream pInputStream, File pFile) throws IOException {
    BufferedInputStream bis = new BufferedInputStream(pInputStream);
    FileOutputStream fos = new FileOutputStream(pFile.getAbsolutePath());
    byte[] buffer = new byte[32768];
    int bytesRead = 0;
    while (bis.available() > 0) {
        bytesRead = bis.read(buffer);/*from  w  ww . j a  v a2s .  co  m*/
        fos.write(buffer, 0, bytesRead);
    }
    bis.close();
    fos.close();
    pFile.deleteOnExit();
}

From source file:brooklyn.util.os.Os.java

/** creates a private temp file which will be deleted on exit;
 * either prefix or ext may be null; /*from   w  w  w.  ja v a  2 s .c  om*/
 * if ext is non-empty and not > 4 chars and not starting with a ., then a dot will be inserted */
public static File newTempFile(String prefix, String ext) {
    String sanitizedPrefix = (prefix != null ? prefix + "-" : "");
    String sanitizedExt = (ext != null ? ext.startsWith(".") || ext.length() > 4 ? ext : "." + ext : "");
    try {
        File tempFile = File.createTempFile(sanitizedPrefix, sanitizedExt, new File(tmp()));
        tempFile.deleteOnExit();
        return tempFile;
    } catch (IOException e) {
        throw Exceptions.propagate(e);
    }
}

From source file:org.cloudifysource.quality.iTests.test.cli.cloudify.util.NewRestTestUtils.java

public static Map<String, File> getMachinesDumpFile(final String restUrl, final String username,
        final String password, final String processors, final long fileZiseLimit,
        final String errMessageContain)
        throws IOException, RestClientException, WrongMessageException, FailedToCreateDumpException {

    // connect to the REST
    RestClient restClient = createAndConnect(restUrl, username, password);

    // get dump data using REST API
    GetMachinesDumpFileResponse response;
    try {/*from www  .  j  ava 2  s  .  com*/
        response = restClient.getMachinesDumpFile(processors, fileZiseLimit);
        if (errMessageContain != null) {
            Assert.fail("RestClientException expected [" + errMessageContain + "]");
        }
        // write the result data to a temporary file.
        Map<String, byte[]> dumpBytesPerIP = response.getDumpBytesPerIP();
        Map<String, File> dumpFilesPerIP = new HashMap<String, File>(dumpBytesPerIP.size());
        for (Entry<String, byte[]> entry : dumpBytesPerIP.entrySet()) {
            File file = File.createTempFile("dump", ".zip");
            file.deleteOnExit();
            FileUtils.writeByteArrayToFile(file, entry.getValue());
            dumpFilesPerIP.put(entry.getKey(), file);
        }
        return dumpFilesPerIP;
    } catch (RestClientException e) {
        String message = e.getMessageFormattedText();
        if (errMessageContain == null) {
            throw new FailedToCreateDumpException(message);
        } else {
            if (!message.contains(errMessageContain)) {
                throw new WrongMessageException(message, errMessageContain);
            }
            return null;
        }
    }
}

From source file:com.centeractive.ws.builder.DefinitionSaveTest.java

public static File getGeneratedFolder(int serviceId) throws WSDLException, IOException {
    URL wsdlUrl = ServiceComplianceTest.getDefinitionUrl(serviceId);
    SoapBuilder builder = new SoapBuilder(wsdlUrl);
    File tempFolder = File.createTempFile("maven-temp", Long.toString(System.nanoTime()));
    if (!tempFolder.delete()) {
        throw new RuntimeException("cannot delete tmp file");
    }/*from  www . j  a  v a  2 s  . c  o m*/
    if (!tempFolder.mkdir()) {
        throw new RuntimeException("cannot create tmp folder");
    }
    String fileName = FilenameUtils.getBaseName(wsdlUrl.toString());
    builder.saveWsdl(fileName, tempFolder);
    tempFolder.deleteOnExit();
    return tempFolder;
}

From source file:course1778.mobileapp.safeMedicare.Main.FamMemFrag.java

public static File stream2file(InputStream in) throws IOException {
    final File tempFile = File.createTempFile(PREFIX, SUFFIX);
    tempFile.deleteOnExit();
    try (FileOutputStream out = new FileOutputStream(tempFile)) {
        IOUtils.copy(in, out);//from w  w  w  .ja va 2  s  . c  om
    }
    return tempFile;
}

From source file:com.alvermont.terraj.fracplanet.io.JarLibraryLoader.java

/**
 * Extracts a file from the jar so it can be found as a library. There
 * is no way to load a library directly from the jar file. Uses the 
 * users current directory to write the jar file, which might not work,
 * should probably fall back to the home dir. We can't use createTempFile
 * for this as we have to preserve the library filename so that dependencies
 * can be correctly resolved. The extracted file is marked for deletion on
 * exit.// w  w w  . ja v  a  2s  .  c  om
 *
 * @param name The name of the file to be extracted
 * @throws IOException if there is an error extracting the library.
 */
public static File extractLibrary(String name) throws IOException {
    try {
        // Gets a stream to the library file

        File temporaryDll = null;

        InputStream inputStream = JarLibraryLoader.class.getResourceAsStream(getLibraryResourceName(name));

        if (inputStream != null) {
            temporaryDll = new File(
                    System.getProperty("user.home") + File.separator + name + getLibraryNameSuffix());

            String dir = System.getProperty("user.home");

            temporaryDll = new File(dir, getLibraryName(name));
            temporaryDll.deleteOnExit();

            FileOutputStream outputStream = new FileOutputStream(temporaryDll);

            byte[] array = new byte[8192];

            for (int i = inputStream.read(array); i != -1; i = inputStream.read(array)) {
                outputStream.write(array, 0, i);
            }

            outputStream.close();
        }

        return temporaryDll;
    } catch (IOException ioe) {
        log.error("IOException loading library", ioe);

        throw ioe;
    }
}

From source file:com.sangupta.jerry.util.ZipUtils.java

/**
 * Read a given file from the ZIP file and store it in a temporary file. The
 * temporary file is set to be deleted on exit of application.
 * /*from  ww w.  j  a  v a  2 s  .  c o m*/
 * @param zipFile
 *            the zip file from which the file needs to be read
 * 
 * @param fileName
 *            the name of the file that needs to be extracted
 * 
 * @return the {@link File} handle for the extracted file in the temp
 *         directory
 * 
 * @throws IllegalArgumentException
 *             if the zipFile is <code>null</code> or the fileName is
 *             <code>null</code> or empty.
 */
public static File readFileFromZip(File zipFile, String fileName) throws FileNotFoundException, IOException {
    if (zipFile == null) {
        throw new IllegalArgumentException("zip file to extract from cannot be null");
    }

    if (AssertUtils.isEmpty(fileName)) {
        throw new IllegalArgumentException("the filename to extract cannot be null/empty");
    }

    LOGGER.debug("Reading {} from {}", fileName, zipFile.getAbsolutePath());

    ZipInputStream stream = null;
    BufferedOutputStream outStream = null;
    File tempFile = null;

    try {
        byte[] buf = new byte[1024];
        stream = new ZipInputStream(new FileInputStream(zipFile));
        ZipEntry entry;
        while ((entry = stream.getNextEntry()) != null) {
            String entryName = entry.getName();
            if (entryName.equals(fileName)) {
                tempFile = File.createTempFile(FilenameUtils.getName(entryName),
                        FilenameUtils.getExtension(entryName));
                tempFile.deleteOnExit();

                outStream = new BufferedOutputStream(new FileOutputStream(tempFile));
                int readBytes;
                while ((readBytes = stream.read(buf, 0, 1024)) > -1) {
                    outStream.write(buf, 0, readBytes);
                }

                stream.close();
                outStream.close();

                return tempFile;
            }
        }
    } finally {
        IOUtils.closeQuietly(stream);
        IOUtils.closeQuietly(outStream);
    }

    return tempFile;
}

From source file:cz.cas.lib.proarc.common.export.mets.JhoveUtility.java

/**
 * Creates the JHOVE context and stores its configuration in a default temp folder.
 * Use {@link JhoveContext#destroy() } to remove temp folder.
 *
 * @return the context/*from   w w  w .ja  va2  s.c  o  m*/
 * @throws MetsExportException failure
 */
public static JhoveContext createContext() throws MetsExportException {
    File temp = new File(FileUtils.getTempDirectory(), "jhove" + UUID.randomUUID().toString());
    if (!temp.mkdir()) {
        throw new MetsExportException("Cannot create " + temp.toString());
    }
    temp.deleteOnExit();
    return createContext(temp);
}

From source file:gov.nasa.ensemble.common.CommonUtils.java

/**
 * Creates a temporary file and adds a shutdown hook for it to be deleted on VM exit. This file is *NOT* guaranteed to be deleted, but this method is still better than calling File.createTempFile.
 * // ww w. ja v  a 2 s.c o m
 * @param prefix
 * @param suffix
 * @return File
 * @throws IOException
 */
public static File createTemporaryFile(String prefix, String suffix) throws IOException {
    File file = File.createTempFile(prefix, suffix);
    file.deleteOnExit();
    return file;
}

From source file:Main.java

public static File getFile(Context context, Uri uri, boolean forceCreation) {

    if (!forceCreation && "file".equalsIgnoreCase(uri.getScheme())) {
        return new File(uri.getPath());
    }/* www  .ja va 2s  .com*/

    File file = null;

    try {
        File root = context.getFilesDir();
        if (root == null) {
            throw new Exception("data dir not found");
        }
        file = new File(root, getFilename(context, uri));
        file.delete();
        InputStream is = context.getContentResolver().openInputStream(uri);
        OutputStream os = new FileOutputStream(file);
        byte[] buf = new byte[1024];
        int cnt = is.read(buf);
        while (cnt > 0) {
            os.write(buf, 0, cnt);
            cnt = is.read(buf);
        }
        os.close();
        is.close();
        file.deleteOnExit();
    } catch (Exception e) {
        Log.e("OpenFile", e.getMessage(), e);
    }
    return file;
}