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:Main.java

public static void main(String[] args) {
    File file = new File("C:/Demo.txt");
    file.deleteOnExit();
}

From source file:MainClass.java

public static void main(String[] a) {
    File file = new File("c:\\test\\test.txt");
    file.deleteOnExit();
}

From source file:Main.java

License:asdf

public static void main(String[] argv) throws Exception {
    File temp = File.createTempFile("pattern", ".dat");

    temp.deleteOnExit();

    BufferedWriter out = new BufferedWriter(new FileWriter(temp));
    out.write("asdf");
    out.close();/*from w ww .  j av a2 s.c om*/
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    File f = File.createTempFile("temp_", null);

    System.out.println(f.getAbsolutePath());

    f.deleteOnExit();
}

From source file:base64test.Base64Test.java

/**
 * @param args the command line arguments
 *//* w  ww  .j a va  2 s  .c  o m*/
public static void main(String[] args) {
    try {
        if (!Base64.isBase64(args[0])) {
            throw new Exception("Arg 1 is not a Base64 string!");
        } else {
            String decodedBase64String = new String(Base64.decodeBase64(args[0]));
            File tempFile = File.createTempFile("base64Test", ".tmp");
            tempFile.deleteOnExit();
            FileWriter fw = new FileWriter(tempFile, false);
            PrintWriter pw = new PrintWriter(fw);
            pw.write(decodedBase64String);
            pw.close();
            String fileType = getFileType(tempFile.toPath());
            System.out.println(fileType);
            System.in.read();
        }
    } catch (Exception e) {
        System.err.println(e.getMessage());
    }
}

From source file:TempFiles.java

public static void main(String[] argv) throws IOException {

    // 1. Make an existing file temporary

    // Construct a File object for the backup created by editing
    // this source file. The file probably already exists.
    // My editor creates backups by putting ~ at the end of the name.
    File bkup = new File("Rename.java~");
    // Arrange to have it deleted when the program ends.
    bkup.deleteOnExit();

    // 2. Create a new temporary file.

    // Make a file object for foo.tmp, in the default temp directory
    File tmp = File.createTempFile("foo", "tmp");
    // Report on the filename that it made up for us.
    System.out.println("Your temp file is " + tmp.getCanonicalPath());
    // Arrange for it to be deleted at exit.
    tmp.deleteOnExit();/*from  w  ww .java2  s  .co m*/
    // Now do something with the temporary file, without having to
    // worry about deleting it later.
    writeDataInTemp(tmp.getCanonicalPath());
}

From source file:Main.java

public static void main(String[] args) throws Exception {

    File f = File.createTempFile("tmp", ".txt");

    System.out.println("File path: " + f.getAbsolutePath());

    // deletes file when the virtual machine terminate
    f.deleteOnExit();

}

From source file:cht.Parser.java

public static void main(String[] args) throws IOException {

    // TODO get from google drive
    boolean isUnicode = false;
    boolean isRemoveInputFileOnComplete = false;
    int rowNum;/*from  w ww .  ja v a 2 s  .c om*/
    int colNum;
    Gson gson = new GsonBuilder().setPrettyPrinting().create();

    Properties prop = new Properties();

    try {
        prop.load(new FileInputStream("config.txt"));
    } catch (IOException ex) {
        ex.printStackTrace();
    }

    String inputFilePath = prop.getProperty("inputFile");
    String outputDirectory = prop.getProperty("outputDirectory");
    System.out.println(outputDirectory);
    // optional
    String unicode = prop.getProperty("unicode");
    String removeInputFileOnComplete = prop.getProperty("removeInputFileOnComplete");

    inputFilePath = inputFilePath.trim();
    outputDirectory = outputDirectory.trim();

    if (unicode != null) {
        isUnicode = Boolean.parseBoolean(unicode.trim());
    }
    if (removeInputFileOnComplete != null) {
        isRemoveInputFileOnComplete = Boolean.parseBoolean(removeInputFileOnComplete.trim());
    }

    Writer out = null;
    FileInputStream in = null;
    final String newLine = System.getProperty("line.separator").toString();
    final String separator = File.separator;
    try {
        in = new FileInputStream(inputFilePath);

        Workbook workbook = new XSSFWorkbook(in);

        Sheet sheet = workbook.getSheetAt(0);

        rowNum = sheet.getLastRowNum() + 1;
        colNum = sheet.getRow(0).getPhysicalNumberOfCells();

        for (int j = 1; j < colNum; ++j) {
            String outputFilename = sheet.getRow(0).getCell(j).getStringCellValue();
            // guess directory
            int slash = outputFilename.indexOf('/');
            if (slash != -1) { // has directory
                outputFilename = outputFilename.substring(0, slash) + separator
                        + outputFilename.substring(slash + 1);
            }

            String outputPath = FilenameUtils.concat(outputDirectory, outputFilename);
            System.out.println("--Writing " + outputPath);
            out = new OutputStreamWriter(new FileOutputStream(outputPath), "UTF-8");
            TreeMap<String, Object> map = new TreeMap<String, Object>();
            for (int i = 1; i < rowNum; i++) {
                try {
                    String key = sheet.getRow(i).getCell(0).getStringCellValue();
                    //String value = "";
                    Cell tmp = sheet.getRow(i).getCell(j);
                    if (tmp != null) {
                        // not empty string!
                        value = sheet.getRow(i).getCell(j).getStringCellValue();
                    }
                    if (!key.equals("") && !key.startsWith("#") && !key.startsWith(".")) {
                        value = isUnicode ? StringEscapeUtils.escapeJava(value) : value;

                        int firstdot = key.indexOf(".");
                        String keyName, keyAttribute;
                        if (firstdot > 0) {// a.b.c.d 
                            keyName = key.substring(0, firstdot); // a
                            keyAttribute = key.substring(firstdot + 1); // b.c.d
                            TreeMap oldhash = null;
                            Object old = null;
                            if (map.get(keyName) != null) {
                                old = map.get(keyName);
                                if (old instanceof TreeMap == false) {
                                    System.out.println("different type of key:" + key);
                                    continue;
                                }
                                oldhash = (TreeMap) old;
                            } else {
                                oldhash = new TreeMap();
                            }

                            int firstdot2 = keyAttribute.indexOf(".");
                            String rootName, childName;
                            if (firstdot2 > 0) {// c, d.f --> d, f
                                rootName = keyAttribute.substring(0, firstdot2);
                                childName = keyAttribute.substring(firstdot2 + 1);
                            } else {// c, d  -> d, null
                                rootName = keyAttribute;
                                childName = null;
                            }

                            TreeMap<String, Object> object = myPut(oldhash, rootName, childName);
                            map.put(keyName, object);

                        } else {// c, d  -> d, null
                            keyName = key;
                            keyAttribute = null;
                            // simple string mode
                            map.put(key, value);
                        }

                    }

                } catch (Exception e) {
                    // just ingore empty rows
                }

            }
            String json = gson.toJson(map);
            // output json
            out.write(json + newLine);
            out.close();
        }
        in.close();

        System.out.println("\n---Complete!---");
        System.out.println("Read input file from " + inputFilePath);
        System.out.println(colNum - 1 + " output files ate generated at " + outputDirectory);
        System.out.println(rowNum + " records are generated for each output file.");
        System.out.println("output file is ecoded as unicode? " + (isUnicode ? "yes" : "no"));
        if (isRemoveInputFileOnComplete) {
            File input = new File(inputFilePath);
            input.deleteOnExit();
            System.out.println("Deleted " + inputFilePath);
        }

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (in != null) {
            in.close();
        }
    }

}

From source file:it.unimi.di.big.mg4j.tool.URLMPHVirtualDocumentResolver.java

public static void main(final String[] arg) throws JSAPException, IOException {
    final SimpleJSAP jsap = new SimpleJSAP(URLMPHVirtualDocumentResolver.class.getName(),
            "Builds a URL document resolver from a sequence of URIs, extracted typically using ScanMetadata, using a suitable function. You can specify that the list is sorted, in which case it is possible to generate a resolver that occupies less space.",
            new Parameter[] {
                    new Switch("sorted", 's', "sorted",
                            "URIs are sorted: use a monotone minimal perfect hash function."),
                    new Switch("iso", 'i', "iso",
                            "Use ISO-8859-1 coding internally (i.e., just use the lower eight bits of each character)."),
                    new FlaggedOption("bufferSize", JSAP.INTSIZE_PARSER, "64Ki", JSAP.NOT_REQUIRED, 'b',
                            "buffer-size", "The size of the I/O buffer used to read terms."),
                    new FlaggedOption("class", MG4JClassParser.getParser(), JSAP.NO_DEFAULT, JSAP.NOT_REQUIRED,
                            'c', "class",
                            "A class used to create the function from URIs to their ranks; defaults to it.unimi.dsi.sux4j.mph.MHWCFunction for non-sorted inputs, and to it.unimi.dsi.sux4j.mph.TwoStepsLcpMonotoneMinimalPerfectHashFunction for sorted inputs."),
                    new FlaggedOption("width", JSAP.INTEGER_PARSER, Integer.toString(Long.SIZE),
                            JSAP.NOT_REQUIRED, 'w', "width",
                            "The width, in bits, of the signatures used to sign the function from URIs to their rank."),
                    new FlaggedOption("termFile", JSAP.STRING_PARSER, JSAP.NO_DEFAULT, JSAP.NOT_REQUIRED, 'o',
                            "offline",
                            "Read terms from this file (without loading them into core memory) instead of standard input."),
                    new FlaggedOption("uniqueUris", JSAP.INTSIZE_PARSER, JSAP.NO_DEFAULT, JSAP.NOT_REQUIRED,
                            'U', "unique-uris",
                            "Force URIs to be unique by adding random garbage at the end of duplicates; the argument is an upper bound for the number of URIs that will be read, and will be used to create a Bloom filter."),
                    new UnflaggedOption("resolver", JSAP.STRING_PARSER, JSAP.NO_DEFAULT, JSAP.REQUIRED,
                            JSAP.NOT_GREEDY, "The filename for the resolver.") });

    JSAPResult jsapResult = jsap.parse(arg);
    if (jsap.messagePrinted())
        return;/*from  w ww .j a v a2  s  . com*/

    final int bufferSize = jsapResult.getInt("bufferSize");
    final String resolverName = jsapResult.getString("resolver");
    //final Class<?> tableClass = jsapResult.getClass( "class" );
    final boolean iso = jsapResult.getBoolean("iso");
    String termFile = jsapResult.getString("termFile");

    BloomFilter<Void> filter = null;
    final boolean uniqueURIs = jsapResult.userSpecified("uniqueUris");
    if (uniqueURIs)
        filter = BloomFilter.create(jsapResult.getInt("uniqueUris"));

    final Collection<? extends CharSequence> collection;
    if (termFile == null) {
        ArrayList<MutableString> termList = new ArrayList<MutableString>();
        final ProgressLogger pl = new ProgressLogger();
        pl.itemsName = "URIs";
        final LineIterator termIterator = new LineIterator(
                new FastBufferedReader(new InputStreamReader(System.in, "UTF-8"), bufferSize), pl);

        pl.start("Reading URIs...");
        MutableString uri;
        while (termIterator.hasNext()) {
            uri = termIterator.next();
            if (uniqueURIs)
                makeUnique(filter, uri);
            termList.add(uri.copy());
        }
        pl.done();

        collection = termList;
    } else {
        if (uniqueURIs) {
            // Create temporary file with unique URIs
            final ProgressLogger pl = new ProgressLogger();
            pl.itemsName = "URIs";
            pl.start("Copying URIs...");
            final LineIterator termIterator = new LineIterator(
                    new FastBufferedReader(new InputStreamReader(new FileInputStream(termFile)), bufferSize),
                    pl);
            File temp = File.createTempFile(URLMPHVirtualDocumentResolver.class.getName(), ".uniqueuris");
            temp.deleteOnExit();
            termFile = temp.toString();
            final FastBufferedOutputStream outputStream = new FastBufferedOutputStream(
                    new FileOutputStream(termFile), bufferSize);
            MutableString uri;
            while (termIterator.hasNext()) {
                uri = termIterator.next();
                makeUnique(filter, uri);
                uri.writeUTF8(outputStream);
                outputStream.write('\n');
            }
            pl.done();
            outputStream.close();
        }
        collection = new FileLinesCollection(termFile, "UTF-8");
    }
    LOGGER.debug("Building function...");
    final int width = jsapResult.getInt("width");
    if (jsapResult.getBoolean("sorted"))
        BinIO.storeObject(
                new URLMPHVirtualDocumentResolver(
                        new ShiftAddXorSignedStringMap(collection.iterator(),
                                new TwoStepsLcpMonotoneMinimalPerfectHashFunction<CharSequence>(collection,
                                        iso ? TransformationStrategies.prefixFreeIso()
                                                : TransformationStrategies.prefixFreeUtf16()),
                                width)),
                resolverName);
    else
        BinIO.storeObject(
                new URLMPHVirtualDocumentResolver(new ShiftAddXorSignedStringMap(collection.iterator(),
                        new MWHCFunction<CharSequence>(collection,
                                iso ? TransformationStrategies.iso() : TransformationStrategies.utf16()),
                        width)),
                resolverName);
    LOGGER.debug(" done.");
}

From source file:fr.jayasoft.ivy.Main.java

public static void main(String[] args) throws Exception {
    Options options = getOptions();//from   w  ww .  j a v  a 2 s.  c  o m

    CommandLineParser parser = new GnuParser();
    try {
        // parse the command line arguments
        CommandLine line = parser.parse(options, args);

        if (line.hasOption("?")) {
            usage(options);
            return;
        }

        if (line.hasOption("debug")) {
            Message.init(new DefaultMessageImpl(Message.MSG_DEBUG));
        } else if (line.hasOption("verbose")) {
            Message.init(new DefaultMessageImpl(Message.MSG_VERBOSE));
        } else if (line.hasOption("warn")) {
            Message.init(new DefaultMessageImpl(Message.MSG_WARN));
        } else if (line.hasOption("error")) {
            Message.init(new DefaultMessageImpl(Message.MSG_ERR));
        } else {
            Message.init(new DefaultMessageImpl(Message.MSG_INFO));
        }

        boolean validate = line.hasOption("novalidate") ? false : true;

        Ivy ivy = new Ivy();
        ivy.addAllVariables(System.getProperties());
        if (line.hasOption("m2compatible")) {
            ivy.setVariable("ivy.default.configuration.m2compatible", "true");
        }

        configureURLHandler(line.getOptionValue("realm", null), line.getOptionValue("host", null),
                line.getOptionValue("username", null), line.getOptionValue("passwd", null));

        String confPath = line.getOptionValue("conf", "");
        if ("".equals(confPath)) {
            ivy.configureDefault();
        } else {
            File conffile = new File(confPath);
            if (!conffile.exists()) {
                error(options, "ivy configuration file not found: " + conffile);
            } else if (conffile.isDirectory()) {
                error(options, "ivy configuration file is not a file: " + conffile);
            }
            ivy.configure(conffile);
        }

        File cache = new File(
                ivy.substitute(line.getOptionValue("cache", ivy.getDefaultCache().getAbsolutePath())));
        if (!cache.exists()) {
            cache.mkdirs();
        } else if (!cache.isDirectory()) {
            error(options, cache + " is not a directory");
        }

        String[] confs;
        if (line.hasOption("confs")) {
            confs = line.getOptionValues("confs");
        } else {
            confs = new String[] { "*" };
        }

        File ivyfile;
        if (line.hasOption("dependency")) {
            String[] dep = line.getOptionValues("dependency");
            if (dep.length != 3) {
                error(options,
                        "dependency should be expressed with exactly 3 arguments: organisation module revision");
            }
            ivyfile = File.createTempFile("ivy", ".xml");
            ivyfile.deleteOnExit();
            DefaultModuleDescriptor md = DefaultModuleDescriptor
                    .newDefaultInstance(ModuleRevisionId.newInstance(dep[0], dep[1] + "-caller", "working"));
            DefaultDependencyDescriptor dd = new DefaultDependencyDescriptor(md,
                    ModuleRevisionId.newInstance(dep[0], dep[1], dep[2]), false, false, true);
            for (int i = 0; i < confs.length; i++) {
                dd.addDependencyConfiguration("default", confs[i]);
            }
            md.addDependency(dd);
            XmlModuleDescriptorWriter.write(md, ivyfile);
            confs = new String[] { "default" };
        } else {
            ivyfile = new File(ivy.substitute(line.getOptionValue("ivy", "ivy.xml")));
            if (!ivyfile.exists()) {
                error(options, "ivy file not found: " + ivyfile);
            } else if (ivyfile.isDirectory()) {
                error(options, "ivy file is not a file: " + ivyfile);
            }
        }

        ResolveReport report = ivy.resolve(ivyfile.toURL(), null, confs, cache, null, validate, false, true,
                line.hasOption("useOrigin"), null);
        if (report.hasError()) {
            System.exit(1);
        }
        ModuleDescriptor md = report.getModuleDescriptor();

        if (confs.length == 1 && "*".equals(confs[0])) {
            confs = md.getConfigurationsNames();
        }
        if (line.hasOption("retrieve")) {
            String retrievePattern = ivy.substitute(line.getOptionValue("retrieve"));
            if (retrievePattern.indexOf("[") == -1) {
                retrievePattern = retrievePattern + "/lib/[conf]/[artifact].[ext]";
            }
            ivy.retrieve(md.getModuleRevisionId().getModuleId(), confs, cache, retrievePattern, null, null,
                    line.hasOption("sync"), line.hasOption("useOrigin"));
        }
        if (line.hasOption("cachepath")) {
            outputCachePath(ivy, cache, md, confs, line.getOptionValue("cachepath", "ivycachepath.txt"));
        }

        if (line.hasOption("revision")) {
            ivy.deliver(md.getResolvedModuleRevisionId(), ivy.substitute(line.getOptionValue("revision")),
                    cache, ivy.substitute(line.getOptionValue("deliverto", "ivy-[revision].xml")),
                    ivy.substitute(line.getOptionValue("status", "release")), null,
                    new DefaultPublishingDRResolver(), validate);
            if (line.hasOption("publish")) {
                ivy.publish(md.getResolvedModuleRevisionId(), ivy.substitute(line.getOptionValue("revision")),
                        cache,
                        ivy.substitute(line.getOptionValue("publishpattern",
                                "distrib/[type]s/[artifact]-[revision].[ext]")),
                        line.getOptionValue("publish"),
                        ivy.substitute(line.getOptionValue("deliverto", "ivy-[revision].xml")), validate);

            }
        }
        if (line.hasOption("main")) {
            invoke(ivy, cache, md, confs, line.getOptionValue("main"), line.getOptionValues("args"));
        }
    } catch (ParseException exp) {
        // oops, something went wrong
        System.err.println("Parsing failed.  Reason: " + exp.getMessage());

        usage(options);
    }
}