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:be.i8c.sag.util.FileUtils.java

/**
 * Copy a directory and it's content/*from w  w w  . j a v  a 2  s  . c  om*/
 *
 * @param from The directory to copy
 * @param to Where to copy it to
 * @param deleteOnExit If true, delete the files once the application has closed.
 * @throws IOException When failed to write to a file
 * @throws FileNotFoundException If a file could not be found
 */
public static void copyDirectory(File from, File to, boolean deleteOnExit) throws IOException {
    File[] children = from.listFiles();
    if (children != null) {
        for (File child : children) {
            // Extract the file
            InputStream in = new FileInputStream(child);
            File outputFile = createFile(new File(to, child.getName()));
            if (deleteOnExit)
                outputFile.deleteOnExit();

            OutputStream out = new FileOutputStream(outputFile);
            try {
                IOUtils.copy(in, out);
            } finally {
                out.flush();
                in.close();
                out.close();
            }
        }
    }
}

From source file:com.vmware.bdd.usermgmt.TestSssdConfigurationGenerator.java

public static void setupSssdTemplates() throws IOException {
    String tmpDirPath = System.getProperty("java.io.tmpdir");

    if (StringUtils.isNotBlank(System.getProperty("serengeti.home.dir"))) {
        System.setProperty("serengeti.home.dir.bak", System.getProperty("serengeti.home.dir"));
    }//from  w  ww  . j  a va2 s  .c o  m
    System.setProperty("serengeti.home.dir", tmpDirPath);

    File usermgmrConfDir = new File(
            System.getProperty("serengeti.home.dir") + File.separator + "conf" + File.separator + "usermgmt");
    usermgmrConfDir.mkdirs();
    usermgmrConfDir.deleteOnExit();

    File tmpFile = new File(usermgmrConfDir, SssdConfigurationGenerator.SSSD_CONF_TEMPLATES + "LDAP");
    tmpFile.createNewFile();
    tmpFile.deleteOnExit();
    FileCopyUtils.copy(readResource(SssdConfigurationGenerator.SSSD_CONF_TEMPLATES + "LDAP"),
            new FileWriter(tmpFile));

    tmpFile = new File(usermgmrConfDir, SssdConfigurationGenerator.SSSD_CONF_TEMPLATES + "AD_AS_LDAP");
    tmpFile.createNewFile();
    tmpFile.deleteOnExit();
    FileCopyUtils.copy(readResource(SssdConfigurationGenerator.SSSD_CONF_TEMPLATES + "AD_AS_LDAP"),
            new FileWriter(tmpFile));
}

From source file:jnative.JNativeCodeLoader.java

/**
 * Locates the native library in the jar (loadble by the classloader really),
 * unpacks it in a temp location, and returns that file. If the native library
 * is not found by the classloader, returns null.
 *//* w  w  w.j  av  a2s  .co m*/
private static File unpackBinaries() {
    // locate the binaries inside the jar
    String fileName = System.mapLibraryName(LIBRARY_NAME);
    String directory = getDirectoryLocation();
    // use the current defining classloader to load the resource
    InputStream is = JNativeCodeLoader.class.getResourceAsStream(directory + "/" + fileName);
    if (is == null) {
        // specific to mac
        // on mac the filename can be either .dylib or .jnilib: try again with the
        // alternate name
        if (getOsName().contains("Mac")) {
            if (fileName.endsWith(".dylib")) {
                fileName = fileName.replace(".dylib", ".jnilib");
            } else if (fileName.endsWith(".jnilib")) {
                fileName = fileName.replace(".jnilib", ".dylib");
            }
            is = JNativeCodeLoader.class.getResourceAsStream(directory + "/" + fileName);
        }
        // the OS-specific library was not found: fall back on the library path
        if (is == null) {
            return null;
        }
    }

    // write the file
    byte[] buffer = new byte[8192];
    OutputStream os = null;
    try {
        // prepare the unpacked file location
        File unpackedFile = File.createTempFile("unpacked-", "-" + fileName);
        // ensure the file gets cleaned up
        unpackedFile.deleteOnExit();

        os = new FileOutputStream(unpackedFile);
        int read = 0;
        while ((read = is.read(buffer)) != -1) {
            os.write(buffer, 0, read);
        }

        // set the execution permission
        unpackedFile.setExecutable(true, false);
        LOG.debug("temporary unpacked path: " + unpackedFile);
        // return the file
        return unpackedFile;
    } catch (IOException e) {
        LOG.error("could not unpack the binaries", e);
        return null;
    } finally {
        try {
            is.close();
        } catch (IOException ignore) {
        }
        if (os != null) {
            try {
                os.close();
            } catch (IOException ignore) {
            }
        }
    }
}

From source file:com.github.rholder.gradle.dependency.DependencyConversionUtil.java

/**
 * Use the Gradle Tooling API to extract dependency information on the
 * given path, returning the root node of the dependency graph.
 *
 * @param projectPath   the path to the target project to load
 * @param toolingLogger instance to use for Gradle tooling log messages
 *//*from   ww  w.  j a  v a2  s. co m*/
public static Map<String, GradleNode> loadProjectDependenciesFromModel(String projectPath,
        final ToolingLogger toolingLogger) {
    if (projectPath == null) {
        return Collections.singletonMap("root", new GradleNode("No Gradle project directory selected..."));
    }

    ProjectConnection connection = GradleConnector.newConnector().forProjectDirectory(new File(projectPath))
            .connect();

    Map<String, GradleNode> dependencyMap = Maps.newHashMap();
    AcumenTreeModel atm;
    try {
        @SuppressWarnings("unchecked")
        BuildActionExecuter<AcumenTreeModel> action = connection.action(new AcumenModelAction());
        action.addProgressListener(new ProgressListener() {
            public void statusChanged(ProgressEvent event) {
                toolingLogger.log(event.getDescription());
            }
        });

        // TODO this needs to be cached

        // extract from classpath
        File initAcumenFile = File.createTempFile("init-acumen", ".gradle");
        initAcumenFile.deleteOnExit();

        // use a custom plugin, if this value is set
        File extractedJarFile;
        String devGradleAcumen = System.getProperty("gradle.view.debug.acumen.jar");
        if (devGradleAcumen == null) {
            extractedJarFile = File.createTempFile("gradle-acumen", ".jar");
            extractedJarFile.deleteOnExit();
            dumpFromClasspath("/gradle-acumen-0.2.0.jar", extractedJarFile);
        } else {
            extractedJarFile = new File(devGradleAcumen);
        }

        acumenTemplateFromClasspath(extractedJarFile, initAcumenFile);

        action.withArguments("--init-script", initAcumenFile.getAbsolutePath());
        File jdkHome = getJdkHome();
        if (jdkHome != null) {
            toolingLogger.log("Using Gradle JAVA_HOME=" + jdkHome);
            action.setJavaHome(jdkHome);
        }
        atm = action.run();

        GradleNode rootNode = convertToGradleNode(atm);
        dependencyMap.put("root", rootNode);
    } catch (Exception e) {
        toolingLogger.log(ExceptionUtils.getFullStackTrace(e));
        throw new RuntimeException(e);
    } finally {
        connection.close();
    }

    return dependencyMap;
}

From source file:com.abiquo.appliancemanager.ApplianceManagerAsserts.java

/**
 * /*from w  w w. j a  va  2s  .  c o  m*/
 * 
 * */

protected static void createBundleDiskFile(final String ovfId, final String snapshot) throws Exception {
    EnterpriseRepositoryService er = ErepoFactory.getRepo(String.valueOf(idEnterprise));

    final String ovfpath = TemplateConventions.getRelativePackagePath(ovfId);
    final String diskFilePathRel = er.getDiskFilePath(ovfId);
    // final String diskFilePathRel = diskFilePath.substring(diskFilePath.lastIndexOf('/'));

    final String path = FilenameUtils.concat(FilenameUtils.concat(er.path(), ovfpath),
            (snapshot + "-snapshot-" + diskFilePathRel));

    // "/opt/testvmrepo/1/rs.bcn.abiquo.com/m0n0wall/000snap000-snapshot-m0n0wall-1.3b18-i386-flat.vmdk"

    File f = new File(path);
    f.createNewFile();
    f.deleteOnExit();

    FileWriter fileWriter = new FileWriter(f);
    for (int i = 0; i < 1000; i++) {
        fileWriter.write(i % 1);
    }
    fileWriter.close();
}

From source file:com.hadoop.compression.lzo.GPLNativeCodeLoader.java

/**
 * Locates the native library in the jar (loadble by the classloader really),
 * unpacks it in a temp location, and returns that file. If the native library
 * is not found by the classloader, returns null.
 *///from ww  w.  j a  v  a2s  .  c o m
private static File unpackBinaries() {
    // locate the binaries inside the jar
    String fileName = System.mapLibraryName(LIBRARY_NAME);
    String directory = getDirectoryLocation();
    // use the current defining classloader to load the resource
    InputStream is = GPLNativeCodeLoader.class.getResourceAsStream(directory + "/" + fileName);
    if (is == null) {
        // specific to mac
        // on mac the filename can be either .dylib or .jnilib: try again with the
        // alternate name
        if (getOsName().contains("Mac")) {
            if (fileName.endsWith(".dylib")) {
                fileName = fileName.replace(".dylib", ".jnilib");
            } else if (fileName.endsWith(".jnilib")) {
                fileName = fileName.replace(".jnilib", ".dylib");
            }
            is = GPLNativeCodeLoader.class.getResourceAsStream(directory + "/" + fileName);
        }
        // the OS-specific library was not found: fall back on the library path
        if (is == null) {
            return null;
        }
    }

    // write the file
    byte[] buffer = new byte[8192];
    OutputStream os = null;
    try {
        // prepare the unpacked file location
        File unpackedFile = File.createTempFile("unpacked-", "-" + fileName);
        // ensure the file gets cleaned up
        unpackedFile.deleteOnExit();

        os = new FileOutputStream(unpackedFile);
        int read = 0;
        while ((read = is.read(buffer)) != -1) {
            os.write(buffer, 0, read);
        }

        // set the execution permission
        unpackedFile.setExecutable(true, false);
        LOG.debug("temporary unpacked path: " + unpackedFile);
        // return the file
        return unpackedFile;
    } catch (IOException e) {
        LOG.error("could not unpack the binaries", e);
        return null;
    } finally {
        try {
            is.close();
        } catch (IOException ignore) {
        }
        if (os != null) {
            try {
                os.close();
            } catch (IOException ignore) {
            }
        }
    }
}

From source file:com.amazonaws.util.FileUtils.java

public static File generateRandomAsciiFile(long byteSize, boolean deleteOnExit) throws IOException {
    File file = File.createTempFile("CryptoTestUtils", ".txt");
    System.out.println("Generating random ASCII file with size: " + byteSize + " at " + file);
    if (deleteOnExit)
        file.deleteOnExit();
    OutputStream out = new FileOutputStream(file);
    int BUFSIZE = 1024 * 8;
    byte[] buf = new byte[1024 * 8];
    long counts = byteSize / BUFSIZE;
    try {/*from w  w  w  .  j a  v  a2s  . c  o  m*/
        while (counts-- > 0) {
            IOUtils.write(fillRandomAscii(buf), out);
        }
        int remainder = (int) byteSize % BUFSIZE;
        if (remainder > 0) {
            buf = new byte[remainder];
            IOUtils.write(fillRandomAscii(buf), out);
        }
    } finally {
        out.close();
    }
    return file;
}

From source file:de.tudarmstadt.ukp.dkpro.tc.crfsuite.writer.CRFSuiteDataWriter.java

public static File writeFeatureFile(FeatureStore featureStore, File aOutputDirectory) throws Exception {
    int totalCountOfInstances = featureStore.getNumberOfInstances();

    File outputFile = new File(aOutputDirectory,
            CRFSuiteAdapter.getInstance().getFrameworkFilename(AdapterNameEntries.featureVectorsFile));
    outputFile.deleteOnExit();

    BufferedWriter bf = new BufferedWriter(new FileWriter(outputFile));

    int lastSeenSeqId = -1;
    boolean seqIdChanged = false;
    for (int ins = 0; ins < totalCountOfInstances; ins++) {
        Instance i = featureStore.getInstance(ins);

        if (i.getSequenceId() != lastSeenSeqId) {
            seqIdChanged = true;// www . j  a v a 2s.c o m
            lastSeenSeqId = i.getSequenceId();
        }

        bf.write(LabelSubstitutor.labelReplacement(i.getOutcome()));
        bf.write("\t");

        List<Feature> features = i.getFeatures();
        for (int idx = 0; idx < features.size(); idx++) {
            Feature f = features.get(idx);
            bf.write(f.getName() + "=" + f.getValue());
            if (idx + 1 < features.size()) {
                bf.write("\t");
            }
        }

        // Mark first line of new sequence with an additional __BOS__
        if (seqIdChanged) {
            bf.write("\t");
            bf.write("__BOS__");
            seqIdChanged = false;
        }

        // Peak ahead - seqEnd reached?
        if (ins + 1 < totalCountOfInstances) {
            Instance next = featureStore.getInstance(ins + 1);
            if (next.getSequenceId() != lastSeenSeqId) {
                appendEOS(bf);
                continue;
            }
        } else if (ins + 1 == totalCountOfInstances) {
            appendEOS(bf);
        }

        bf.write("\n");
    }
    bf.close();

    return outputFile;
}

From source file:Main.java

/**
 * Attempts to delete the specified file. If it cannot be deleted, it is
 * flagged as deleteOnExit.//from  w  w w . j  av a  2 s .c  o m
 */
static public void deleteFile(File p_tmpFile) {
    try {
        p_tmpFile.delete();
    } catch (Exception ex) {
        // ignore - tmp file may not be deletable on windows
    } finally {
        if (p_tmpFile.exists()) {
            // Tell VM to delete file on exit when it still exists.
            p_tmpFile.deleteOnExit();
        }
    }
}

From source file:atg.tools.dynunit.test.util.FileUtil.java

public static File newTempFile() throws IOException {
    logger.entry();//from w w  w  .  ja  va 2  s .  c om
    final File tempFile = File.createTempFile("dynunit-", null);
    tempFile.deleteOnExit();
    return logger.exit(tempFile);
}