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:de.tudarmstadt.ukp.dkpro.core.api.resources.ResourceUtils.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. This method should not be used for creating executable
 * binaries. For this purpose, getUrlAsExecutable should be used.
 *
 * @param aUrl//  ww w .  j a  v  a2 s . co m
 *            the URL.
 * @param aCache
 *            use the cache or not.
 * @param aForceTemp
 *            always create a temporary file, even if the URL is already a file.
 * @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, boolean aForceTemp) throws IOException {
    // If the URL already points to a file, there is not really much to do.
    if (!aForceTemp && "file".equalsIgnoreCase(aUrl.getProtocol())) {
        try {
            return new File(aUrl.toURI());
        } catch (URISyntaxException e) {
            throw new IOException(e);
        }
    }

    synchronized (urlFileCache) {
        // 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.toString());
        if (!aCache || (file == null) || !file.exists()) {
            // Create a temporary file and try to preserve the file extension
            String suffix = FilenameUtils.getExtension(aUrl.getPath());
            if (suffix.length() == 0) {
                suffix = "temp";
            }
            String name = FilenameUtils.getBaseName(aUrl.getPath());

            // 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.

            InputStream is = null;
            OutputStream os = null;
            try {
                is = aUrl.openStream();
                os = new FileOutputStream(file);
                copy(is, os);
            } finally {
                closeQuietly(is);
                closeQuietly(os);
            }

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

        return file;
    }
}

From source file:edu.umn.msi.tropix.grid.io.transfer.impl.TransferContextFactoryImplTest.java

public void download(final DownloadType type) throws Exception {
    final TransferServiceContextReference ref = new TransferServiceContextReference();
    final GlobusCredential proxy = EasyMock.createMock(GlobusCredential.class);
    final Credential credential = Credentials.get(proxy);
    final File file = File.createTempFile("tpx", "");
    file.deleteOnExit();
    EasyMock.expect(utils.get(EasyMock.same(ref), EasyMock.same(proxy)));
    if (type != DownloadType.EXCEPTION) {
        EasyMock.expectLastCall().andReturn(new ByteArrayInputStream("Hello".getBytes()));
    } else {/*from w w w .  jav  a 2  s  .co  m*/
        EasyMock.expectLastCall().andThrow(new Exception());
    }
    EasyMock.replay(utils);
    final InputContext downloadContext = factory.getDownloadContext(ref, credential);
    if (type.equals(DownloadType.FILE) || type == DownloadType.EXCEPTION) {
        downloadContext.get(file);
    } else if (type.equals(DownloadType.STREAM)) {
        downloadContext.get(new FileOutputStream(file));
    }
    assert FileUtils.readFileToString(file).equals("Hello");
}

From source file:org.datagator.api.client.SpooledRowBuffer.java

public SpooledRowBuffer(int cacheLimit) throws IOException {
    this.cache = new ArrayList<Object[]>();
    File tempFile = File.createTempFile("dg_Cache_", ".tmp");
    tempFile.deleteOnExit();
    this.cacheFile = new RandomAccessFile(tempFile, "rw");
    this.cacheLimit = cacheLimit;
}

From source file:au.org.ala.delta.intkey.model.DisplayInputTest.java

@Test
public void testDisplayInput() throws Exception {
    IntkeyContext context = loadDataset("/dataset/sample/intkey.ink");

    for (Character ch : context.getDataset().getCharactersAsList()) {
        if (!(ch instanceof MultiStateCharacter)) {
            System.out.println(ch.getCharacterId());
        }/*from w w  w .j a v  a2 s  .  co m*/
    }

    File tempLogFile = File.createTempFile("DisplayInputTest", null);
    tempLogFile.deleteOnExit();

    context.setLogFile(tempLogFile);

    File tempJournalFile = File.createTempFile("DisplayInputTest", null);
    tempJournalFile.deleteOnExit();

    context.setJournalFile(tempJournalFile);

    URL directiveFileUrl = getClass().getResource("/input/test_directives_file.txt");
    File directivesFile = new File(directiveFileUrl.toURI());

    // first, process the sample file as a preferences file, and ensure that
    // the directive call is not output
    // to the journal or log

    new PreferencesDirective().parseAndProcess(context, directivesFile.getAbsolutePath());

    String logFileAsString = FileUtils.readFileToString(tempLogFile);
    assertFalse(logFileAsString.contains("*DEFINE CHARACTERS preferencestest 1"));

    String journalFileAsString = FileUtils.readFileToString(tempJournalFile);
    assertFalse(journalFileAsString.contains("*DEFINE CHARACTERS preferencestest 1"));

    // now, process the sample file as an input file. As DISPLAY INPUT has
    // not been set to ON,
    // the directive call should still not turn up in the log or journal
    // files

    new FileInputDirective().parseAndProcess(context, directivesFile.getAbsolutePath());

    logFileAsString = FileUtils.readFileToString(tempLogFile);
    assertFalse(logFileAsString.contains("*DEFINE CHARACTERS preferencestest 1"));

    journalFileAsString = FileUtils.readFileToString(tempJournalFile);
    assertFalse(journalFileAsString.contains("*DEFINE CHARACTERS preferencestest 1"));

    // now set DISPLAY INPUT to ON, and process the directives file as an input file again. 

    new DisplayInputDirective().parseAndProcess(context, "ON");

    new FileInputDirective().parseAndProcess(context, directivesFile.getAbsolutePath());

    logFileAsString = FileUtils.readFileToString(tempLogFile);
    assertTrue(logFileAsString.contains("*DEFINE CHARACTERS preferencestest 1"));

    journalFileAsString = FileUtils.readFileToString(tempJournalFile);
    assertTrue(journalFileAsString.contains("*DEFINE CHARACTERS preferencestest 1"));
}

From source file:com.talis.inject.guice.PropertiesConfiguredModuleFactoryTest.java

@Test
public void readPropertiesFromFileSpecifiedBySystemProperty() throws Exception {

    File tmpFile = File.createTempFile("injector-module", ".properties");
    tmpFile.deleteOnExit();
    FileUtils.writeStringToFile(tmpFile, String.format("%s=%s",
            PropertiesConfiguredModuleFactory.MODULE_PROPERTY, TestModuleThree.class.getName()));
    System.clearProperty(PropertiesConfiguredModuleFactory.PROPERTIES_LOCATION_PROP);

    try {/*from www.  j  av  a  2  s.c  o  m*/
        System.setProperty(PropertiesConfiguredModuleFactory.PROPERTIES_LOCATION_PROP,
                tmpFile.getAbsolutePath());
        Module[] modules = new PropertiesConfiguredModuleFactory().getModules();
        assertEquals(1, modules.length);
        assertTrue(TestModuleThree.class.isInstance(modules[0]));
    } finally {
        System.clearProperty(PropertiesConfiguredModuleFactory.PROPERTIES_LOCATION_PROP);
    }
}

From source file:de.fau.cs.osr.hddiff.perfsuite.util.SerializationUtils.java

public File storeWomCompactTemp(PageRevDiffNode prdn, Revision rev, DiffNode node) throws Exception {
    File file = File.createTempFile(makeCompactPrefix(prdn, rev), ".xml", tempDir);
    file.deleteOnExit();
    try (FileOutputStream output = new FileOutputStream(file)) {
        byte[] bytes = serializer.serialize(getOwnerDocument((Wom3Node) node.getNativeNode()),
                WomSerializer.SerializationFormat.XML, true, false);
        IOUtils.write(bytes, output);//from  www  .  j a  v a 2s  .  co m
        return file;
    }
}

From source file:edu.harvard.med.screensaver.io.libraries.rnai.WorkbookLibraryContentsParser.java

public void convert() throws IOException {
    Workbook _workbook = new Workbook("Library Contents Input Stream", getStream());
    File tmpFile = File.createTempFile("workbook", ".csv");
    tmpFile.deleteOnExit();
    log.debug("converting workbook into csv file: " + tmpFile.getAbsolutePath());
    CSVPrintWriter writer = new CSVPrintWriter(new BufferedWriter(new FileWriter(tmpFile)), "\n",
            FIELD_DELIMITER);//www .  j  ava2 s .  c  o  m
    Iterator<Worksheet> worksheetsIterator = _workbook.iterator();
    int prevSheetLastRecord = 0;
    int record = 0;
    _worksheetRecordRanges = Maps.newHashMap();
    while (worksheetsIterator.hasNext()) {
        Worksheet worksheet = worksheetsIterator.next().forOrigin(0, FIRST_DATA_ROW);
        Iterator<Row> rowsIterator = worksheet.iterator();
        while (rowsIterator.hasNext()) {
            for (Cell cell : rowsIterator.next()) {
                writer.print(cell.getAsString());
            }
            writer.println();
            ++record;
        }
        IntRange worksheetRecordRange = new IntRange(prevSheetLastRecord, record);
        _worksheetRecordRanges.put(worksheetRecordRange, worksheet.getName());
        prevSheetLastRecord = record;
    }
    writer.close();
    _reader = new BufferedReader(new FileReader(tmpFile));
    log.debug("done converting workbook into csv file");
}

From source file:com.hortonworks.streamline.streams.catalog.configuration.ConfigFileWriterTest.java

@Test
public void writeJavaPropertiesConfigToFile() throws Exception {
    Map<String, String> configuration = createDummyConfiguration();

    File destPath = Files.createTempFile("config", "properties").toFile();
    destPath.deleteOnExit();

    writer.writeConfigToFile(ConfigFileType.PROPERTIES, configuration, destPath);
    assertTrue(destPath.exists());//  w  w  w.j  a v  a 2 s .c o  m
    try (InputStream is = new FileInputStream(destPath)) {
        String content = IOUtils.toString(is);
        System.out.println("Test print: properties content - " + content);
    }

    try (InputStream is = new FileInputStream(destPath)) {
        Properties prop = new Properties();
        prop.load(is);

        for (Map.Entry<String, String> property : configuration.entrySet()) {
            assertEquals(property.getValue().toString(), prop.getProperty(property.getKey()));
        }
    }
}

From source file:edu.umn.msi.tropix.grid.io.transfer.impl.TransferContextFactoryImplTest.java

public void upload(final UploadType type) throws Exception {
    final TransferServiceContextReference ref = new TransferServiceContextReference();
    final GlobusCredential proxy = EasyMock.createMock(GlobusCredential.class);
    final Credential credential = Credentials.get(proxy);
    final OutputContext uc = factory.getUploadContext(ref, credential);
    final File file = File.createTempFile("tpx", "");
    file.deleteOnExit();
    FileUtils.writeStringToFile(file, "Moo!");
    final ByteArrayOutputStream bStream = new ByteArrayOutputStream();
    utils.put(EasyMockUtils.copy(bStream), EasyMock.same(ref), EasyMock.same(proxy));
    if (type.equals(UploadType.EXCEPTION)) {
        EasyMock.expectLastCall().andThrow(new Exception());
    }//from   w  w  w  .ja v  a2 s.c  o  m
    EasyMock.replay(utils);
    if (type.equals(UploadType.FILE) || type.equals(UploadType.EXCEPTION)) {
        uc.put(file);
    } else if (type.equals(UploadType.STREAM)) {
        uc.put(new FileInputStream(file));
    } else if (type.equals(UploadType.BYTES)) {
        uc.put(FileUtils.readFileToByteArray(file));
    }
    EasyMock.verify(utils);
    assert "Moo!".equals(new String(bStream.toByteArray()));
}

From source file:net.lmxm.ute.executers.tasks.FileSystemDeleteTaskExecuterTest.java

/**
 * Test delete files file does not exist.
 *//*  w ww .j  a va2  s .co m*/
public void testDeleteFilesFileDoesNotExist() {
    final File file = new File(TMP_DIR, "TESTFILE.TEST");
    file.deleteOnExit();

    assertFalse(file.exists());

    executer.deleteFiles(file.getAbsolutePath(), null, STOP_ON_ERROR);

    assertFalse(file.exists());
}