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:edu.unc.lib.dl.util.ZipFileUtil.java

/**
 * Create a temporary directory, unzip the contents of the given zip file to
 * it, and return the directory.//from ww w.  ja va2  s  . c om
 * 
 * If anything goes wrong during this process, clean up the temporary
 * directory and throw an exception.
 */
public static File unzipToTemp(InputStream zipStream) throws IOException {
    // get a temporary directory to work with
    File tempDir = File.createTempFile("ingest", null);
    tempDir.delete();
    tempDir.mkdir();
    tempDir.deleteOnExit();
    log.debug("Unzipping to temporary directory: " + tempDir.getPath());
    try {
        unzip(zipStream, tempDir);
        return tempDir;
    } catch (IOException e) {
        // attempt cleanup, then re-throw
        org.apache.commons.io.FileUtils.deleteDirectory(tempDir);
        throw e;
    }
}

From source file:de.uni_koeln.spinfo.maalr.sigar.SigarWrapper.java

private static void initialize() {
    logger.info("Initializing...");
    String libBase = "/hyperic-sigar-1.6.5/sigar-bin/lib/";
    try {/* ww w.  j av  a  2s.c o m*/
        String prefix = "libsigar";
        if (SystemUtils.IS_OS_WINDOWS) {
            prefix = "sigar";
        }
        String arch = getSystemArch();
        String suffix = getSystemSuffix();
        String resourceName = prefix + "-" + arch + "-" + suffix;

        logger.info("Native library: " + resourceName);

        String resource = libBase + resourceName;
        URL toLoad = SigarWrapper.class.getResource(resource);
        File home = new File(System.getProperty("user.home"));
        File libs = new File(home, ".maalr/libs/sigar");
        libs.mkdirs();
        File tmp = new File(libs, resourceName);
        tmp.deleteOnExit();
        FileOutputStream fos = new FileOutputStream(tmp);
        InputStream in = toLoad.openStream();
        int i;
        while ((i = in.read()) != -1) {
            fos.write(i);
        }
        in.close();
        fos.close();
        logger.info("Library copied to " + tmp.getAbsolutePath());
        String oldPath = System.getProperty("java.library.path");
        System.setProperty("java.library.path", oldPath + SystemUtils.PATH_SEPARATOR + libs.getAbsolutePath());
        logger.info("java.library.path updated: " + System.getProperty("java.library.path"));
        executors = Executors.newScheduledThreadPool(1, new ThreadFactory() {

            public Thread newThread(Runnable r) {
                Thread t = new Thread(r);
                t.setDaemon(true);
                return t;
            }
        });
        logger.info("Initialization completed.");
    } catch (Exception e) {
        logger.error("Failed to initialize!", e);
    }
}

From source file:cz.zcu.kiv.eegdatabase.wui.components.utils.FileUtils.java

public static boolean deleteOnExitQuietly(File file) {

    if (file == null) {
        return false;
    }/*w w w.  java2  s . c  o  m*/

    try {
        file.deleteOnExit();
        return true;
    } catch (Exception e) {
        log.warn(e.getMessage(), e);
        return false;
    }
}

From source file:ml.dmlc.xgboost4j.java.NativeLibrary.java

private static File extract(String libPath, ClassLoader classLoader)
        throws IOException, IllegalArgumentException {

    // Split filename to prefix and suffix (extension)
    String filename = libPath.substring(libPath.lastIndexOf('/') + 1);
    int lastDotIdx = filename.lastIndexOf('.');
    String prefix = "";
    String suffix = null;/*from   w  w  w  . j  av a  2s  . c  o  m*/
    if (lastDotIdx >= 0 && lastDotIdx < filename.length() - 1) {
        prefix = filename.substring(0, lastDotIdx);
        suffix = filename.substring(lastDotIdx);
    }

    // Prepare temporary file
    File temp = File.createTempFile(prefix, suffix);
    temp.deleteOnExit();

    // Open and check input stream
    InputStream is = classLoader.getResourceAsStream(libPath);
    if (is == null) {
        throw new FileNotFoundException("File " + libPath + " was not found inside JAR.");
    }

    // Open output stream and copy data between source file in JAR and the temporary file
    try {
        Files.copy(is, temp.toPath(), StandardCopyOption.REPLACE_EXISTING);
    } finally {
        is.close();
    }

    return temp;
}

From source file:com.dragome.web.helpers.serverside.DragomeCompilerLauncher.java

private static Classpath process(Classpath classPath, DragomeConfigurator configurator) {
    try {//from w w w. j ava  2 s.  co m
        String path = null;

        String tempDir = System.getProperty("java.io.tmpdir");
        File tmpDir = new File(tempDir + File.separatorChar + "dragomeTemp");
        Path tmpPath = tmpDir.toPath();
        FileUtils.deleteDirectory(tmpDir);
        Files.createDirectories(tmpPath);
        File file = Files.createTempFile(tmpPath, "dragome-merged-", ".jar").toFile();
        file.deleteOnExit();
        path = file.getAbsolutePath();

        try (JarOutputStream jos = new JarOutputStream(new FileOutputStream(file))) {
            List<ClasspathEntry> entries = classPath.getEntries();
            for (ClasspathEntry classpathEntry : entries)
                classpathEntry.copyFilesToJar(jos, new DefaultClasspathFileFilter() {
                    private ArrayList<String> keepClass = new ArrayList<>();

                    public boolean accept(ClasspathFile classpathFile) {
                        boolean result = super.accept(classpathFile);

                        String entryName = classpathFile.getPath();
                        if (!keepClass.contains(entryName)) {
                            keepClass.add(entryName);

                            if (entryName.endsWith(".js") || entryName.endsWith(".class")
                                    || entryName.contains("MANIFEST") || entryName.contains(".html")
                                    || entryName.contains(".css"))
                                result &= true;
                        }
                        return result;
                    }
                });
        }

        if (configurator.isRemoveUnusedCode()) {
            return runProguard(file, configurator);
        } else
            return new Classpath(JarClasspathEntry.createFromPath(path));
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:com.hp.alm.ali.idea.action.attachment.AttachmentAgmLinkDownloadTask.java

private static File createTempFile() {
    try {//  w ww. j a  v a  2 s  .  c  om
        File tempFile = File.createTempFile("agmlink", "");
        tempFile.deleteOnExit();
        return tempFile;
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.cloudera.director.aws.rds.RDSEncryptionInstanceClasses.java

/**
 * Gets a test instance of this class that uses only the given encryption
 * instance classes./*ww  w.j  av  a 2s. co  m*/
 *
 * @param encryptionInstanceClasses list of instance classes that support storage encryption
 * @param localizationContext the localization context
 * @return new encryption instance classes object
 */
public static RDSEncryptionInstanceClasses getTestInstance(final List<String> encryptionInstanceClasses,
        LocalizationContext localizationContext) {
    Map<String, String> encryptionInstanceClassesMap = Maps.newHashMap();
    for (String instanceClass : encryptionInstanceClasses) {
        encryptionInstanceClassesMap.put(instanceClass, "true");
    }
    PropertyResolver resolver = PropertyResolvers.newMapPropertyResolver(encryptionInstanceClassesMap);

    File tempDir = Files.createTempDir();
    tempDir.deleteOnExit();

    RDSEncryptionInstanceClassesConfigProperties configProperties = new RDSEncryptionInstanceClassesConfigProperties(
            new SimpleConfiguration(), tempDir, localizationContext);
    return new RDSEncryptionInstanceClasses(configProperties, resolver);
}

From source file:gobblin.source.extractor.extract.google.GoogleCommon.java

private static File copyToLocal(FileSystem fs, Path keyPath) throws IOException {
    java.nio.file.Path tmpKeyPath = Files.createTempFile(GoogleCommon.class.getSimpleName(), "tmp",
            PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("rwx------")));
    File copied = tmpKeyPath.toFile();
    copied.deleteOnExit();

    fs.copyToLocalFile(keyPath, new Path(copied.getAbsolutePath()));
    return copied;
}

From source file:com.cloudera.director.aws.rds.RDSEndpoints.java

/**
 * Gets a test instance of this class that uses only the given endpoints.
 *
 * @param endpoints           map of RDS regions to endpoint URLs
 * @param localizationContext the localization context
 * @return new endpoints object//from   w  w w.  j  av  a  2s.c o  m
 */
public static RDSEndpoints getTestInstance(final Map<String, String> endpoints,
        LocalizationContext localizationContext) {
    PropertyResolver rdsEndpointsResolver = PropertyResolvers.newMapPropertyResolver(endpoints);
    File tempDir = Files.createTempDir();
    tempDir.deleteOnExit();
    RDSEndpointsConfigProperties rdsEndpointsConfigProperties = new RDSEndpointsConfigProperties(
            new SimpleConfiguration(), tempDir, localizationContext);
    return new RDSEndpoints(rdsEndpointsConfigProperties, rdsEndpointsResolver);
}

From source file:de.huberlin.german.korpling.laudatioteitool.App.java

private static void validate(String arg, String corpusSchemeURL, String documentSchemeURL,
        String prepartionSchemeURL) {
    File f = new File(arg);
    if (!f.exists()) {
        System.err.println("File " + f.getAbsolutePath() + " does not exist");
        System.exit(-2);//from   ww  w  .j  a  v a2  s  . c o m
    }

    if (f.isDirectory()) {
        try {
            File out = File.createTempFile("tmpvalidation", ".xml");
            out.deleteOnExit();
            MergeTEI merge = new MergeTEI(f, out, corpusSchemeURL, documentSchemeURL, prepartionSchemeURL);
            merge.merge();

            out.delete();

            // if we got until there without exception the document is valid
            System.out.println("Validation successfull");
            System.exit(0);
        } catch (IOException ex) {
            log.error("Could not create temporary file", ex);
        } catch (LaudatioException ex) {
            System.err.println(ex.getLocalizedMessage());
        }
    } else {
        try {
            File out = Files.createTempDir();

            SplitTEI split = new SplitTEI(f, out, corpusSchemeURL, documentSchemeURL, prepartionSchemeURL);
            split.split();

            deleteTemporaryDirectory(out);

            // if we got until there without exception the document is valid
            System.out.println("Validation successfull");
            System.exit(0);
        } catch (IOException ex) {
            log.error("Could not create temporary file", ex);
        } catch (LaudatioException ex) {
            System.err.println(ex.getLocalizedMessage());
        }
    }

    // non-valid per default
    System.exit(1);
}