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:fi.solita.phantomrunner.util.FileUtils.java

/**
 * Extracts the given resource to user's temporary directory (by creating a unique directory underneath
 * it). Will delete that file and created directories on system exit if deleteOnExit is true.
 * //from www.  j a  v a2 s. c o  m
 * @param resource Resource to be extracted
 * @param subPath Slash (character '/') separated path of the sub-directories which should be created
 * @param deleteOnExit If the resource and created sub-directories should be deleted
 * 
 * @return File handle to the created file in the temporary directory
 */
public static File extractResourceToTempDirectory(Resource resource, String subPath, boolean deleteOnExit)
        throws IOException {
    final File tempDir = Files.createTempDir();
    if (deleteOnExit)
        tempDir.deleteOnExit();

    File lastDir = tempDir;
    for (String subDir : subPath.split("/")) {
        // if the subPath starts or ends with '/' we'll get empty strings too
        if (StringUtils.hasLength(subDir)) {
            lastDir = new File(lastDir, subDir);
            lastDir.mkdir();
            if (deleteOnExit)
                lastDir.deleteOnExit();
        }
    }

    final File resFile = new File(lastDir, resource.getFilename());
    resFile.createNewFile();
    if (deleteOnExit)
        resFile.deleteOnExit();

    IOUtil.copy(resource.getInputStream(), new FileWriter(resFile), "UTF-8");

    return resFile;
}

From source file:eu.planets_project.ifr.core.techreg.formats.DroidConfig.java

/**
 * @return The location of the DROID signature file taken from the
 *          Droid configuration properties file
 *///from www .j a v  a  2  s  .c o m
public static String getSigFileLocation() {
    // String to hold the location
    String sigFileLocation = null;
    // Get the configuration object from the ServiceConfig util
    try {
        Configuration conf = ServiceConfig.getConfiguration(COMMON_CONF_FILE_NAME);
        // Create the file name from the properties
        sigFileLocation = conf.getString(SIG_FILE_LOC_KEY) + File.separator + conf.getString(SIG_FILE_NAME_KEY);
    } catch (ConfigurationException e) {
        log.severe("Could not find configuration file! " + e);
    }
    log.info("DROID Signature File location:" + sigFileLocation);
    // Check if the sigFileLocation is sane, and override with internal resource if not:
    File sfl = null;
    if (sigFileLocation != null)
        sfl = new File(sigFileLocation);
    if (sfl == null || !sfl.exists() || !sfl.isFile()) {
        try {
            File tmp = File.createTempFile("DroidSigFile", "xml");
            tmp.deleteOnExit();
            IOUtils.copy(DroidConfig.class.getResourceAsStream("/droid/DROID_SignatureFile.xml"),
                    new FileOutputStream(tmp));
            sigFileLocation = tmp.getAbsolutePath();
            log.info("Wrote cached Droid sig file to " + sigFileLocation);
        } catch (IOException e) {
            e.printStackTrace();
            log.severe("Could not generate external Droid Sig File.");
        }
    }
    return sigFileLocation;
}

From source file:Main.java

public static File UpdateZipFromPath(String sZipFile, String sPath) throws Exception {
    File tmpFile = File.createTempFile("z4zip-tmp-", ".zip");
    tmpFile.deleteOnExit();
    ZipFile inZip = new ZipFile(sZipFile);
    ZipOutputStream outZip = new ZipOutputStream(new FileOutputStream(tmpFile.getPath()));

    Enumeration<? extends ZipEntry> entries = inZip.entries();
    while (entries.hasMoreElements()) {
        ZipEntry e = entries.nextElement();
        outZip.putNextEntry(e);// w  w  w  . j  a  v a 2s.c o m
        if (!e.isDirectory()) {
            File f = new File(sPath + "/" + e.getName());
            if (f.exists()) {
                copy(new FileInputStream(f.getPath()), outZip);
            } else {
                copy(inZip.getInputStream(e), outZip);
            }
        }
        outZip.closeEntry();
    }
    inZip.close();
    outZip.close();
    return tmpFile;
}

From source file:Main.java

static File makeTempJar(File moduleFile) throws IOException {
    String prefix = moduleFile.getName();
    if (prefix.endsWith(".jar") || prefix.endsWith(".JAR")) { // NOI18N
        prefix = prefix.substring(0, prefix.length() - 4);
    }//from   w  w  w .  j av  a  2s  .  co m
    if (prefix.length() < 3)
        prefix += '.';
    if (prefix.length() < 3)
        prefix += '.';
    if (prefix.length() < 3)
        prefix += '.';
    String suffix = "-test.jar"; // NOI18N
    File physicalModuleFile = File.createTempFile(prefix, suffix);
    physicalModuleFile.deleteOnExit();
    InputStream is = new FileInputStream(moduleFile);
    try {
        OutputStream os = new FileOutputStream(physicalModuleFile);
        try {
            byte[] buf = new byte[4096];
            int i;
            while ((i = is.read(buf)) != -1) {
                os.write(buf, 0, i);
            }
        } finally {
            os.close();
        }
    } finally {
        is.close();
    }
    return physicalModuleFile;
}

From source file:jfix.zk.Medias.java

public static File asFile(Media media) {
    try {/* www .  ja va2s . c  om*/
        File directory = Files.createTempDirectory("jfix-media").toFile();
        directory.deleteOnExit();
        File file = new File(directory.getPath() + File.separator + media.getName());
        OutputStream output = new FileOutputStream(file);
        if (media.isBinary()) {
            InputStream input = Medias.asStream(media);
            IOUtils.copy(input, output);
            input.close();
        } else {
            Reader input = Medias.asReader(media);
            IOUtils.copy(input, output);
            input.close();
        }
        output.close();
        return file;
    } catch (Exception e) {
        throw new RuntimeException(e.getMessage(), e);
    }
}

From source file:ja.lingo.engine.util.EngineFiles.java

public static File createTempFile(String prefix) throws IOException {
    String tempDir = calculateTemp();

    Files.ensureDirectoryExists(tempDir);

    String fileName = tempDir + File.separator + prefix + "." + tempFileSuffixCounter++;

    File file = new File(fileName).getAbsoluteFile();
    file.deleteOnExit();
    return file;/*from   w  w  w .  jav a2  s  . c  om*/
}

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

/**
 * Download the file at the given location URL and store it as a temporary
 * file on disk. The temporary file is set to be deleted at the exit of the
 * application.//w  w  w.  j ava  2  s.  c  o m
 * 
 * @param url
 *            absolute URL of the file
 * 
 * @return {@link File} handle of the temporary file that was written to
 *         disk if successful, <code>null</code> otherwise.
 * 
 * @throws IOException
 *             in case something fails
 */
public static File downloadToTempFile(String url) throws IOException {
    String extension = UriUtils.extractExtension(url);
    File tempFile = File.createTempFile("download", extension);
    tempFile.deleteOnExit();

    logger.debug("Downloading {} to {}", url, tempFile.getAbsolutePath());

    try {
        WebRequest.get(url).execute().writeToFile(tempFile);
        return tempFile;
    } catch (HttpResponseException e) {
        logger.error("HTTP response did not yield an OK status", e);
    } catch (IOException e) {
        logger.error("Unable to download url to temp file", e);
    }

    return null;
}

From source file:Main.java

private static String createPKCS11ConfigFile(String pkcs11LibPath) {
    File f = null;
    PrintWriter writer = null;//  w ww  .jav a2s. c  o  m
    try {
        f = File.createTempFile("pkcs11", ".cfg");
        f.deleteOnExit();
        writer = new PrintWriter(new FileOutputStream(f));
        writer.println("name = verinice");
        writer.println("description = verinice PKCS#11 configuration");
        writer.println("library = " + pkcs11LibPath);
        writer.close();
    } catch (IOException e) {
        return null;
    } finally {
        if (writer != null)
            writer.close();
    }

    return f.getAbsolutePath();
}

From source file:com.linkedin.pinot.tools.admin.command.StartZookeeperCommand.java

public static File createAutoDeleteTempDir() {
    File tempdir = Files.createTempDir();
    tempdir.delete();//  w w  w  .  ja v a2 s.c  om
    tempdir.mkdir();

    tempdir.deleteOnExit();
    return tempdir;
}

From source file:com.sap.prd.mobile.ios.mios.ScriptRunner.java

private static File copyScript(String script, File workingDirectory) throws IOException {
    if (!workingDirectory.exists())
        if (!workingDirectory.mkdirs())
            throw new IOException("Cannot create directory '" + workingDirectory + "'.");

    final File scriptFile = new File(workingDirectory, getScriptFileName(script));
    scriptFile.deleteOnExit();

    OutputStream os = null;/*from   w w w  .j  a v a 2s. c  o m*/
    InputStream is = null;

    try {
        is = ScriptRunner.class.getResourceAsStream(script);

        if (is == null)
            throw new FileNotFoundException(script + " not found.");

        os = FileUtils.openOutputStream(scriptFile);

        IOUtils.copy(is, os);
    } finally {
        IOUtils.closeQuietly(is);
        IOUtils.closeQuietly(os);
    }

    Forker.forkProcess(System.out, null, "chmod", "755", scriptFile.getCanonicalPath());
    return scriptFile;
}