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:org.dkpro.lab.Util.java

/**
 * Make the given URL available as a file. A temporary file is created and
 * deleted upon a regular shutdown of the JVM. If the parameter {@code
 * aCache} is {@code true}, the temporary file is remembered in a cache and
 * if a file is requested for the same URL at a later time, the same file is
 * returned again. If the previously created file has been deleted
 * meanwhile, it is recreated from the URL.
 *
 * @param aUrl/*from w w  w  . j  a  v a  2 s  . c o m*/
 *            the URL.
 * @param aCache
 *            use the cache or not.
 * @return a file created from the given URL.
 * @throws IOException
 *             if the URL cannot be accessed to (re)create the file.
 */
public static synchronized File getUrlAsFile(URL aUrl, boolean aCache) throws IOException {
    // If the URL already points to a file, there is not really much to do.
    if ("file".equals(aUrl.getProtocol())) {
        try {
            return new File(aUrl.toURI());
        } catch (URISyntaxException e) {
            throw new IOException(e);
        }
    }

    // Lets see if we already have a file for this URL in our cache. Maybe
    // the file has been deleted meanwhile, so we also check if the file
    // actually still exists on disk.
    File file = urlFileCache.get(aUrl);
    if (!aCache || (file == null) || !file.exists()) {
        // Create a temporary file and try to preserve the file extension
        String suffix = ".temp";
        String name = new File(aUrl.getPath()).getName();
        int suffixSep = name.indexOf(".");
        if (suffixSep != -1) {
            suffix = name.substring(suffixSep + 1);
            name = name.substring(0, suffixSep);
        }

        // Get a temporary file which will be deleted when the JVM shuts
        // down.
        file = File.createTempFile(name, suffix);
        file.deleteOnExit();

        // Now copy the file from the URL to the file.
        shoveAndClose(aUrl.openStream(), new FileOutputStream(file));

        // Remember the file
        if (aCache) {
            urlFileCache.put(aUrl, file);
        }
    }

    return file;
}

From source file:net.sf.jasperreports.eclipse.util.FileUtils.java

public static File createTempDir(String prefix) throws IOException {
    final File sysTempDir = new File(System.getProperty("java.io.tmpdir")); //$NON-NLS-1$
    File newTempDir;
    final int maxAttempts = 9;
    int attemptCount = 0;
    do {// ww  w  . j  a va  2  s.  c  o m
        attemptCount++;
        if (attemptCount > maxAttempts)
            throw new IOException(NLS.bind(Messages.FileUtils_ImpossibleToCreateTempDirectory, maxAttempts));
        String dirName = prefix + System.currentTimeMillis();// gUUID.randomUUID().toString();
        newTempDir = new File(sysTempDir, dirName);
    } while (newTempDir.exists());

    if (newTempDir.mkdirs()) {
        newTempDir.deleteOnExit();
        newTempDir.setWritable(true, false);
        newTempDir.setReadable(true, false);
        return newTempDir;
    } else
        throw new IOException(
                NLS.bind(Messages.FileUtils_UnableToCreateDirectory, newTempDir.getAbsolutePath()));
}

From source file:net.sf.taverna.raven.helloworld.HelloWorld.java

public void run(PrintStream out) throws IOException {
    File tmpFile = File.createTempFile("helloworld", "test");
    tmpFile.deleteOnExit();
    FileUtils.writeStringToFile(tmpFile, TEST_DATA, "utf8");
    String read = FileUtils.readFileToString(tmpFile, "utf8");
    out.print(read);//from   w  ww.  ja v a  2s.  c  o  m
}

From source file:org.argouml.application.Main.java

private static void firstGATEDownload() {
    if (sessionID == null || taskID == null)
        return;//from  w  w  w .ja  v a 2  s . c o m
    ActionShowTask.taskDescription = GATEHelper
            .retrieve("/ShowTask?onlydescription=true&taskid=" + Main.taskID);
    if (ActionShowTask.taskDescription == "") {
        JOptionPane.showMessageDialog(null,
                "Verbindungsaufbau zum Server fehlgeschlagen.\nBitte erneut probieren oder E-Mail an sven.strickroth@tu-clausthal.de.");
        Main.taskID = null;
    }
    if (sID != null) {
        // download latest file
        HttpEntity result = GATEHelper.retrieveEntity("/ShowFile/loesung.zargo?sid=" + sID);
        // open file
        if (result != null) {
            File tmpFile;
            try {
                tmpFile = File.createTempFile("argoumlloesung", ".zargo");
                tmpFile.deleteOnExit();
                FileOutputStream os = new FileOutputStream(tmpFile);
                result.writeTo(os);
                os.close();
                projectName = tmpFile.getAbsolutePath();
            } catch (IOException e) {
            }
        }
    }
}

From source file:com.gargoylesoftware.htmlunit.HttpWebConnection.java

/**
 * Reads the content of the stream and saves it in memory or on the file system.
 * @param is the stream to read// w w  w .ja v  a 2 s  .  c  o m
 * @param maxInMemory the maximumBytes to store in memory, after which save to a local file
 * @return a wrapper around the downloaded content
 * @throws IOException in case of read issues
 */
public static DownloadedContent downloadContent(final InputStream is, final int maxInMemory)
        throws IOException {
    if (is == null) {
        return new DownloadedContent.InMemory(new byte[] {});
    }
    final ByteArrayOutputStream bos = new ByteArrayOutputStream();

    final byte[] buffer = new byte[1024];
    int nbRead;
    try {
        while ((nbRead = is.read(buffer)) != -1) {
            bos.write(buffer, 0, nbRead);
            if (bos.size() > maxInMemory) {
                // we have exceeded the max for memory, let's write everything to a temporary file
                final File file = File.createTempFile("htmlunit", ".tmp");
                file.deleteOnExit();
                try (final FileOutputStream fos = new FileOutputStream(file)) {
                    bos.writeTo(fos); // what we have already read
                    IOUtils.copyLarge(is, fos); // what remains from the server response
                }
                return new DownloadedContent.OnFile(file, true);
            }
        }
    } catch (final ConnectionClosedException e) {
        LOG.warn("Connection was closed while reading from stream.", e);
        return new DownloadedContent.InMemory(bos.toByteArray());
    } catch (final IOException e) {
        // this might happen with broken gzip content
        LOG.warn("Exception while reading from stream.", e);
        return new DownloadedContent.InMemory(bos.toByteArray());
    } finally {
        IOUtils.closeQuietly(is);
    }

    return new DownloadedContent.InMemory(bos.toByteArray());
}

From source file:com.microsoft.azure.hdinsight.common.StreamUtil.java

public static File getResourceFile(String resource) throws IOException {
    File file = null;/*from  w  ww  .j  ava 2 s . com*/
    URL res = streamUtil.getClass().getResource(resource);

    if (res.toString().startsWith("jar:")) {
        InputStream input = null;
        OutputStream out = null;

        try {
            input = streamUtil.getClass().getResourceAsStream(resource);
            file = File.createTempFile(String.valueOf(new Date().getTime()), ".tmp");
            out = new FileOutputStream(file);

            int read;
            byte[] bytes = new byte[1024];

            while ((read = input.read(bytes)) != -1) {
                out.write(bytes, 0, read);
            }
        } finally {
            if (input != null) {
                input.close();
            }

            if (out != null) {
                out.flush();
                out.close();
            }

            if (file != null) {
                file.deleteOnExit();
            }
        }

    } else {
        file = new File(res.getFile());
    }

    return file;
}

From source file:de.bund.bfr.fskml.PythonScriptTest.java

public void testScript() throws IOException {

    // Creates temporary file. Fails the test if an error occurs.
    File f = File.createTempFile("temp", "");
    f.deleteOnExit();

    String origScript = "Hello World";
    FileUtils.writeStringToFile(f, origScript, "UTF-8");
    PythonScript pyScript = new PythonScript(f);

    assertEquals(origScript, pyScript.getScript());
}

From source file:net.sf.taverna.raven.helloworld.TestHelloWorld.java

@Test
public void mainWithFilename() throws IOException {
    File tmpFile = File.createTempFile(getClass().getCanonicalName(), "test");
    tmpFile.deleteOnExit();
    assertTrue(tmpFile.isFile());/*from  www.j  a  v a 2s.c  o  m*/
    String fileContent = FileUtils.readFileToString(tmpFile, "utf8");
    assertEquals("File was not empty", "", fileContent);

    HelloWorld.main(new String[] { tmpFile.getAbsolutePath() });
    fileContent = FileUtils.readFileToString(tmpFile, "utf8");
    assertEquals("File did not contain expected output", HelloWorld.TEST_DATA, fileContent);
}

From source file:de.bund.bfr.fskml.RScriptTest.java

public void testScript() throws IOException {

    // Creates temporary file. Fails the test if an error occurs.
    File f = File.createTempFile("temp", "");
    f.deleteOnExit();

    String origScript = "# This is a comment line: It should not appear in the simplified version\n"
            + "library(triangle)\n" // Test library command without quotes
            + "library(\"dplyr\")\n" // Test library command with double quotes
            + "library('devtools')\n" // Test library command with simple quotes
            + "library(foreign) # (a)\n" // Test library command followed by a comment (with parentheses)
            + "source('other.R')\n" // Source command with simple quotes
            + "source(\"other2.R\")\n" // Source command with double quotes
            + "hist(result, breaks=50, main=\"PREVALENCE OF PARENT FLOCKS\")\n";
    FileUtils.writeStringToFile(f, origScript, "UTF-8");
    RScript rScript = new RScript(f);

    assertEquals(origScript, rScript.getScript());
    assertEquals(Arrays.asList("triangle", "dplyr", "devtools", "foreign"), rScript.getLibraries());
    assertEquals(Arrays.asList("other.R", "other2.R"), rScript.getSources());
}

From source file:net.grinder.util.LogCompressUtilTest.java

@Test
public void testLogCompressDecompress() throws IOException {
    File file = new File(LogCompressUtilTest.class.getResource("/grinder1.properties").getFile());
    byte[] zippedContent = LogCompressUtils.compress(file);
    File createTempFile2 = File.createTempFile("a22aa", ".zip");
    createTempFile2.deleteOnExit();
    FileUtils.writeByteArrayToFile(createTempFile2, zippedContent);
    File createTempFile = File.createTempFile("a22", "tmp");
    LogCompressUtils.decompress(zippedContent, createTempFile);
    assertThat(createTempFile.exists(), is(true));
    byte[] unzippedContent = FileUtils.readFileToByteArray(createTempFile);
    assertThat(unzippedContent, is(FileUtils.readFileToByteArray(file)));
}