Example usage for java.io File exists

List of usage examples for java.io File exists

Introduction

In this page you can find the example usage for java.io File exists.

Prototype

public boolean exists() 

Source Link

Document

Tests whether the file or directory denoted by this abstract pathname exists.

Usage

From source file:Main.java

public static void main(String[] argv) {
    // Create a File object
    File dummyFile = new File("dummy.txt");

    // Check for the file's existence
    boolean fileExists = dummyFile.exists();
    if (fileExists) {
        System.out.println("The dummy.txt  file exists.");
    } else {/*from w w  w . j a v a 2  s  . c o m*/

        System.out.println("The dummy.txt  file does  not  exist.");
    }

}

From source file:Main.java

public static void main(String[] argv) throws Exception {
    File f = new File("name.txt");

    if (!f.exists()) {
        System.out.println("File not found.");
        return;/*from   www .  ja  v a2 s  . co  m*/
    }
    if (f.canRead())
        System.out.println("  Readable");
    else
        System.out.println("  Not Readable");

    if (f.canWrite())
        System.out.println("  Writable");
    else
        System.out.println("  Not Writable");
    System.out.println("  Last modified on " + new Date(f.lastModified()));

    long t = Calendar.getInstance().getTimeInMillis();
    if (!f.setLastModified(t))
        System.out.println("Can't set time.");

    if (!f.setReadOnly())
        System.out.println("Can't set to read-only.");

    if (f.canRead())
        System.out.println("  Readable");
    else
        System.out.println("  Not Readable");

    if (f.canWrite())
        System.out.println("  Writable");
    else
        System.out.println("  Not Writable");
    System.out.println("  Last modified on " + new Date(f.lastModified()));

    if (!f.setWritable(true, false))
        System.out.println("Can't return to read/write.");

    if (f.canRead())
        System.out.println("  Readable");
    else
        System.out.println("  Not Readable");

    if (f.canWrite())
        System.out.println("  Writable");
    else
        System.out.println("  Not Writable");
}

From source file:MakeDirectories.java

public static void main(String[] args) {
    if (args.length < 1)
        usage();//from   w  ww.ja  va  2 s.c o  m
    if (args[0].equals("-r")) {
        if (args.length != 3)
            usage();
        File old = new File(args[1]), rname = new File(args[2]);
        old.renameTo(rname);
        fileData(old);
        fileData(rname);
        return; // Exit main
    }
    int count = 0;
    boolean del = false;
    if (args[0].equals("-d")) {
        count++;
        del = true;
    }
    count--;
    while (++count < args.length) {
        File f = new File(args[count]);
        if (f.exists()) {
            System.out.println(f + " exists");
            if (del) {
                System.out.println("deleting..." + f);
                f.delete();
            }
        } else { // Doesn't exist
            if (!del) {
                f.mkdirs();
                System.out.println("created " + f);
            }
        }
        fileData(f);
    }
}

From source file:tests.JSONOutput.java

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

    ObjectMapper mapper = new ObjectMapper();
    File file = new File("./examples/");
    if (!file.exists()) {
        file.mkdir();//ww w  . jav a  2  s.c om
    }

    {
        Keyspace k = new Keyspace("DDD");
        mapper.writeValue(new File("./examples/keyspace.json"), k);

        {
            Table t = new Table(k, "tableName", "pk", "pkt");
            t.addColumn(new Column("columnName", "columnType"));

            mapper.writeValue(new File("./examples/table.json"), t);

        }

        {
            Table t = new Table();
            t.setKeyspace(k);
            t.setName("tableName");
            TableQuery query = new TableQuery();
            query.setTable(t);
            query.setCondition("WHERE name='bob' AND score >= 40");
            mapper.writeValue(new File("./examples/query.json"), query);

        }

    }
}

From source file:gov.nih.nci.caaersinstaller.util.CsmJaasFileCopier.java

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

    //      File csmJaasTemplateFile = new File("/Users/Moni/temp/installer/postgres.csm_jaas.config");
    //      File csmJassConfigFile = new File("/Users/Moni/temp/installer/csm_jaas.config");

    File csmJaasTemplateFile = new File(args[0]);
    File csmJassConfigFile = new File(args[1]);

    if (csmJassConfigFile.exists()) {
        //append content of csmJaasTemplateFile to existing csmJaasConfigFile
        String csmJaasTemplateFileContent = FileUtils.readFileToString(csmJaasTemplateFile);
        StringBuilder stringBuilder = new StringBuilder(FileUtils.readFileToString(csmJassConfigFile));

        int start = stringBuilder.indexOf("caaers {");
        if (start != -1) {
            //If caaers context exisits then replace it.
            int end = stringBuilder.indexOf("};", start);
            end = end + 2;//from   www .jav a 2  s .  c  o m
            stringBuilder.replace(start, end, csmJaasTemplateFileContent);
        } else {
            //if caaers context does not exist then add it 
            stringBuilder.append("\n");
            stringBuilder.append("\n");
            stringBuilder.append(csmJaasTemplateFileContent);
        }

        FileUtils.writeStringToFile(csmJassConfigFile, stringBuilder.toString());
        System.out.println("Modified csm_jaas.config to add caaers context");

    } else {
        //Create a new File with Contents of csmJaasTemplateFile
        FileUtils.copyFile(csmJaasTemplateFile, csmJassConfigFile);
        System.out.println("Created csm_jaas.config");

    }
}

From source file:com.sazneo.export.formatter.Main.java

public static void main(String... args) {

    Log logger = LogFactory.getLog(Main.class);

    if (args.length != 3) {
        logger.error("Usage: java Main <stylesheet> <export xml file> <output dir>");
        System.exit(1);//  www  . j a  va  2s .  c o m
    }

    String styleSheetPath = args[0];
    File styleSheet = new File(styleSheetPath);

    String exportXmlPath = args[1];
    File exportXml = new File(exportXmlPath);

    String outPutDirPath = args[2];
    File outputDir = new File(outPutDirPath);
    if (!outputDir.exists()) {
        outputDir.mkdirs();
    }

    try {
        File outputFile = new File(outputDir, "export.html");
        FileOutputStream outputStream = new FileOutputStream(outputFile);
        HtmlFormatter formatter = new HtmlFormatter(styleSheet, exportXml, outputStream);
        formatter.transform();
        FileProcessor fileProcessor = new FileProcessor(exportXml, outputDir);
        fileProcessor.process();

    } catch (IOException e) {
        logger.error(MessageFormat.format("Failed to create export.html at {0}:\n {1}", outPutDirPath, e));
    }
}

From source file:ZipDemo.java

public static void main(String[] args) throws Exception {
    for (int i = 0; i < args.length; ++i) {
        String uncompressed = "";
        File f = new File(args[i]);

        if (f.exists()) {
            BufferedReader br = new BufferedReader(new FileReader(f));

            String line = "";
            StringBuffer buffer = new StringBuffer();

            while ((line = br.readLine()) != null)
                buffer.append(line);/*from   ww  w .j av  a 2s . c  om*/

            br.close();
            uncompressed = buffer.toString();
        } else {
            uncompressed = args[i];
        }

        byte[] compressed = ZipDemo.compress(uncompressed);

        String compressedAsString = new String(compressed);

        byte[] bytesFromCompressedAsString = compressedAsString.getBytes();

        bytesFromCompressedAsString.equals(compressed);
        System.out.println(ZipDemo.uncompress(compressed));
        System.out.println(ZipDemo.uncompress(compressedAsString));
    }
}

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

/**
 * The entry point./*from   w w  w .j a va 2s.c o m*/
 *
 * @param args the arguments
 * @throws IOException if an error occurs
 */
public static void main(final String[] args) throws IOException {
    if (args.length == 0) {
        System.out.println("HTML file location is not provided");
        return;
    }

    final File file = new File(args[0]);
    if (!file.exists()) {
        System.out.println("File does not exist " + file.getAbsolutePath());
    }

    System.out.println("        /**");
    System.out.println("         * @throws Exception if an error occurs");
    System.out.println("         */");
    System.out.println("        @Test");
    System.out.println("        @Alerts()");
    System.out.println("        public void test() throws Exception {");

    final List<String> lines = FileUtils.readLines(file, TextUtil.DEFAULT_CHARSET);
    for (int i = 0; i < lines.size(); i++) {
        final String line = lines.get(i);
        if (i == 0) {
            System.out.println("            final String html = \"" + line.replace("\"", "\\\"") + "\\n\"");
        } else {
            System.out.print("                + \"" + line.replace("\"", "\\\"") + "\\n\"");
            if (i == lines.size() - 1) {
                System.out.print(";");
            }
            System.out.println();
        }
    }
    System.out.println("            loadPageWithAlerts2(html);");
    System.out.println("        }");
}

From source file:cc.twittertools.index.ExtractTweetidsFromCollection.java

@SuppressWarnings("static-access")
public static void main(String[] args) throws Exception {
    Options options = new Options();

    options.addOption(OptionBuilder.withArgName("dir").hasArg().withDescription("source collection directory")
            .create(COLLECTION_OPTION));

    CommandLine cmdline = null;//from   w w  w .  j  av a2 s .com
    CommandLineParser parser = new GnuParser();
    try {
        cmdline = parser.parse(options, args);
    } catch (ParseException exp) {
        System.err.println("Error parsing command line: " + exp.getMessage());
        System.exit(-1);
    }

    if (!cmdline.hasOption(COLLECTION_OPTION)) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(ExtractTweetidsFromCollection.class.getName(), options);
        System.exit(-1);
    }

    String collectionPath = cmdline.getOptionValue(COLLECTION_OPTION);

    File file = new File(collectionPath);
    if (!file.exists()) {
        System.err.println("Error: " + file + " does not exist!");
        System.exit(-1);
    }

    StatusStream stream = new JsonStatusCorpusReader(file);

    Status status;
    while ((status = stream.next()) != null) {
        System.out.println(status.getId() + "\t" + status.getScreenname());
    }
}

From source file:edu.illinois.cs.cogcomp.nlp.tokenizer.HashCollisionReport.java

/**
 * Read each test file in the directory, tokenize and create the token view. Then check for
 * collisions.//from   www .  j a  va2 s. c o  m
 * @param args
 * @throws IOException 
 */
public static void main(String[] args) throws IOException {
    if (args.length == 0)
        error("Must pass in the name of a directory with files to test against.");
    File dir = new File(args[0]);
    if (!dir.exists()) {
        error("The directory did not exist : " + dir);
    }
    if (!dir.isDirectory()) {
        error("The path was not a directory : " + dir);
    }
    File[] files = dir.listFiles();
    for (File file : files) {
        if (file.isFile()) {
            String normal = FileUtils.readFileToString(file);
            TextAnnotationBuilder tabldr = new TokenizerTextAnnotationBuilder(new StatefulTokenizer());
            TextAnnotation taNormal = tabldr.createTextAnnotation("test", "normal", normal);
            List<Constituent> normalToks = taNormal.getView(ViewNames.TOKENS).getConstituents();
            HashMap<Integer, Constituent> hashmap = new HashMap<>();

            // add each constituent to the map keyed by it's hashcode. Check first to see if the hashcode
            // is already used, if it is report it.
            for (Constituent c : normalToks) {
                int code = c.hashCode();
                if (hashmap.containsKey(code)) {
                    Constituent dup = hashmap.get(code);
                    System.err.println(c + " == " + dup);
                } else {
                    hashmap.put(code, c);
                }
            }
        }
    }

}