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:cc.wikitools.lucene.ScoreWikipediaArticle.java

@SuppressWarnings("static-access")
public static void main(String[] args) throws Exception {
    Options options = new Options();
    options.addOption(//from w  w w  . j ava  2  s .  c om
            OptionBuilder.withArgName("path").hasArg().withDescription("index location").create(INDEX_OPTION));
    options.addOption(
            OptionBuilder.withArgName("num").hasArg().withDescription("article id").create(ID_OPTION));
    options.addOption(
            OptionBuilder.withArgName("string").hasArg().withDescription("article title").create(TITLE_OPTION));
    options.addOption(
            OptionBuilder.withArgName("string").hasArg().withDescription("query text").create(QUERY_OPTION));

    CommandLine cmdline = null;
    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(ID_OPTION) || cmdline.hasOption(TITLE_OPTION)) || !cmdline.hasOption(INDEX_OPTION)
            || !cmdline.hasOption(QUERY_OPTION)) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(ScoreWikipediaArticle.class.getName(), options);
        System.exit(-1);
    }

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

    String queryText = cmdline.getOptionValue(QUERY_OPTION);

    WikipediaSearcher searcher = new WikipediaSearcher(indexLocation);
    PrintStream out = new PrintStream(System.out, true, "UTF-8");

    if (cmdline.hasOption(ID_OPTION)) {
        out.println("score: "
                + searcher.scoreArticle(queryText, Integer.parseInt(cmdline.getOptionValue(ID_OPTION))));
    } else {
        out.println("score: " + searcher.scoreArticle(queryText, cmdline.getOptionValue(TITLE_OPTION)));
    }

    searcher.close();
    out.close();
}

From source file:io.github.azige.mages.Cli.java

public static void main(String[] args) {

    Options options = new Options().addOption("h", "help", false, "print this message")
            .addOption(Option.builder("r").hasArg().argName("bundle").desc("set the ResourceBundle").build())
            .addOption(Option.builder("l").hasArg().argName("locale").desc("set the locale").build())
            .addOption(Option.builder("t").hasArg().argName("template").desc("set the template").build())
            .addOption(Option.builder("p").hasArg().argName("plugin dir")
                    .desc("set the directory to load plugins").build())
            .addOption(Option.builder("f").desc("force override existed file").build());
    try {/*ww w  . jav a 2s . com*/
        CommandLineParser parser = new DefaultParser();
        CommandLine cl = parser.parse(options, args);

        if (cl.hasOption('h')) {
            printHelp(System.out, options);
            return;
        }

        MagesSiteGenerator msg = new MagesSiteGenerator(new File("."), new File("."));

        String[] fileArgs = cl.getArgs();
        if (fileArgs.length < 1) {
            msg.addTask(".");
        } else {
            for (String path : fileArgs) {
                msg.addTask(path);
            }
        }

        if (cl.hasOption("t")) {
            msg.setTemplate(new File(cl.getOptionValue("t")));
        }

        if (cl.hasOption("r")) {
            msg.setResource(new File(cl.getOptionValue("r")));
        } else {
            File resource = new File("Resource.properties");
            if (resource.exists()) {
                msg.setResource(resource);
            }
        }

        if (cl.hasOption("p")) {
            msg.setPluginDir(new File(cl.getOptionValue("p")));
        }

        if (cl.hasOption("f")) {
            msg.setForce(true);
        }

        msg.start();
    } catch (ParseException ex) {
        System.err.println(ex.getMessage());
        printHelp(System.err, options);
    }
}

From source file:com.cohesionforce.AvroToParquet.java

public static void main(String[] args) {

    String inputFile = null;//from www.j a  va  2s. com
    String outputFile = null;

    HelpFormatter formatter = new HelpFormatter();
    // create Options object
    Options options = new Options();

    // add t option
    options.addOption("i", true, "input avro file");
    options.addOption("o", true, "ouptut Parquet file");
    CommandLineParser parser = new DefaultParser();
    CommandLine cmd;
    try {
        cmd = parser.parse(options, args);
        inputFile = cmd.getOptionValue("i");
        if (inputFile == null) {
            formatter.printHelp("AvroToParquet", options);
            return;
        }
        outputFile = cmd.getOptionValue("o");
    } catch (ParseException exc) {
        System.err.println("Problem with command line parameters: " + exc.getMessage());
        return;
    }

    File avroFile = new File(inputFile);

    if (!avroFile.exists()) {
        System.err.println("Could not open file: " + inputFile);
        return;
    }
    try {

        DatumReader<GenericRecord> datumReader = new GenericDatumReader<GenericRecord>();
        DataFileReader<GenericRecord> dataFileReader;
        dataFileReader = new DataFileReader<GenericRecord>(avroFile, datumReader);
        Schema avroSchema = dataFileReader.getSchema();

        // choose compression scheme
        CompressionCodecName compressionCodecName = CompressionCodecName.SNAPPY;

        // set Parquet file block size and page size values
        int blockSize = 256 * 1024 * 1024;
        int pageSize = 64 * 1024;

        String base = FilenameUtils.removeExtension(avroFile.getAbsolutePath()) + ".parquet";
        if (outputFile != null) {
            File file = new File(outputFile);
            base = file.getAbsolutePath();
        }

        Path outputPath = new Path("file:///" + base);

        // the ParquetWriter object that will consume Avro GenericRecords
        ParquetWriter<GenericRecord> parquetWriter;
        parquetWriter = new AvroParquetWriter<GenericRecord>(outputPath, avroSchema, compressionCodecName,
                blockSize, pageSize);
        for (GenericRecord record : dataFileReader) {
            parquetWriter.write(record);
        }
        dataFileReader.close();
        parquetWriter.close();
    } catch (IOException e) {
        System.err.println("Caught exception: " + e.getMessage());
    }
}

From source file:fr.gael.dhus.database.util.RestoreDatabase.java

/**
 * @param args/*from ww  w.  j a v a 2s  .  c  om*/
 * @throws IllegalAccessException 
 * @throws IOException 
 */
public static void main(String[] args) throws IllegalAccessException, IOException {
    if (args.length != 2) {
        throw new IllegalArgumentException(RestoreDatabase.class.getCanonicalName()
                + ": Wrong arguments <source path> <destination path>.");
    }

    File dump = new File(args[0]);
    File db = new File(args[1]);

    logger.info("Restoring " + dump.getPath() + " into " + db.getPath() + ".");

    if (!db.exists())
        throw new IllegalArgumentException(RestoreDatabase.class.getCanonicalName()
                + ": Input database path not found (\"" + db.getPath() + "\").");

    if (!dump.exists())
        throw new IllegalArgumentException(RestoreDatabase.class.getCanonicalName()
                + ": Input database dump path not found (\"" + db.getPath() + "\").");

    FileUtils.deleteDirectory(db);
    FileUtils.copyDirectory(dump, db);

    logger.info("Dump properly restored, please restart system now.");
}

From source file:com.temenos.interaction.rimdsl.generator.launcher.Main.java

public static void main(String[] args) {
    // handle command line options
    final Options options = new Options();
    OptionBuilder.withArgName("src");
    OptionBuilder.withDescription("Model source");
    OptionBuilder.hasArg();//from  w  w  w. j  a  va  2  s .  co m
    OptionBuilder.isRequired();
    OptionBuilder.withValueSeparator(' ');
    Option optSrc = OptionBuilder.create("src");

    OptionBuilder.withArgName("targetdir");
    OptionBuilder.withDescription("Generator target directory");
    OptionBuilder.hasArg();
    OptionBuilder.isRequired();
    OptionBuilder.withValueSeparator(' ');
    Option optTargetDir = OptionBuilder.create("targetdir");

    options.addOption(optSrc);
    options.addOption(optTargetDir);

    // create the command line parser
    final CommandLineParser parser = new GnuParser();
    CommandLine line = null;
    try {
        line = parser.parse(options, args);
    } catch (final ParseException exp) {
        System.err.println("Parsing arguments failed.  Reason: " + exp);
        wrongCall(options);
        return;
    }

    // execute the generator
    Injector injector = new RIMDslStandaloneSetup().createInjectorAndDoEMFRegistration();
    Generator generator = injector.getInstance(Generator.class);
    File srcFile = new File(line.getOptionValue(optSrc.getArgName()));
    if (srcFile.exists()) {
        boolean result = false;
        if (srcFile.isDirectory()) {
            result = generator.runGeneratorDir(srcFile.getPath(),
                    line.getOptionValue(optTargetDir.getArgName()));
        } else {
            result = generator.runGenerator(srcFile.getPath(), line.getOptionValue(optTargetDir.getArgName()));
        }
        System.out.println("Code generation finished [" + result + "]");
    } else {
        System.out.println("Src dir not found.");
    }

}

From source file:com.temenos.interaction.rimdsl.generator.launcher.MainSpringPRD.java

public static void main(String[] args) {
    // handle command line options
    final Options options = new Options();
    OptionBuilder.withArgName("src");
    OptionBuilder.withDescription("Model source");
    OptionBuilder.hasArg();//from w  w  w.  ja va 2 s.  c  o  m
    OptionBuilder.isRequired();
    OptionBuilder.withValueSeparator(' ');
    Option optSrc = OptionBuilder.create("src");

    OptionBuilder.withArgName("targetdir");
    OptionBuilder.withDescription("Generator target directory");
    OptionBuilder.hasArg();
    OptionBuilder.isRequired();
    OptionBuilder.withValueSeparator(' ');
    Option optTargetDir = OptionBuilder.create("targetdir");

    options.addOption(optSrc);
    options.addOption(optTargetDir);

    // create the command line parser
    final CommandLineParser parser = new GnuParser();
    CommandLine line = null;
    try {
        line = parser.parse(options, args);
    } catch (final ParseException exp) {
        System.err.println("Parsing arguments failed.  Reason: " + exp);
        wrongCall(options);
        return;
    }

    // execute the generator
    Injector injector = new RIMDslStandaloneSetupSpringPRD().createInjectorAndDoEMFRegistration();
    Generator generator = injector.getInstance(Generator.class);
    File srcFile = new File(line.getOptionValue(optSrc.getArgName()));
    if (srcFile.exists()) {
        boolean result = false;
        if (srcFile.isDirectory()) {
            result = generator.runGeneratorDir(srcFile.getPath(),
                    line.getOptionValue(optTargetDir.getArgName()));
        } else {
            result = generator.runGenerator(srcFile.getPath(), line.getOptionValue(optTargetDir.getArgName()));
        }
        System.out.println("Code generation finished [" + result + "]");
    } else {
        System.out.println("Src dir not found.");
    }

}

From source file:de.tudarmstadt.ukp.experiments.dip.wp1.documents.Step10RemoveEmptyDocuments.java

public static void main(String[] args) throws IOException {
    // input dir - list of xml query containers
    File inputDir = new File(args[0]);

    // output dir
    File outputDir = new File(args[1]);
    if (!outputDir.exists()) {
        outputDir.mkdirs();/*from   w w w  .j av  a  2  s . c o  m*/
    }

    boolean crop = args.length >= 3 && "crop".equals(args[2]);

    // first find the maximum of zero-sized documents
    int maxMissing = 7;

    /*
    // iterate over query containers
    for (File f : FileUtils.listFiles(inputDir, new String[] { "xml" }, false)) {
    QueryResultContainer queryResultContainer = QueryResultContainer
            .fromXML(FileUtils.readFileToString(f, "utf-8"));
            
    // first find the maximum of zero-sized documents in a query
    int missingInQuery = 0;
            
    for (QueryResultContainer.SingleRankedResult rankedResults : queryResultContainer.rankedResults) {
        // boilerplate removal
        if (rankedResults.plainText == null || rankedResults.plainText.isEmpty()) {
            missingInQuery++;
        }
    }
            
    maxMissing = Math.max(missingInQuery, maxMissing);
    }
    */

    System.out.println("Max zeroLengthDocuments in query: " + maxMissing);
    // max is 7 = we're cut-off at 93

    // iterate over query containers
    for (File f : FileUtils.listFiles(inputDir, new String[] { "xml" }, false)) {
        QueryResultContainer queryResultContainer = QueryResultContainer
                .fromXML(FileUtils.readFileToString(f, "utf-8"));

        List<QueryResultContainer.SingleRankedResult> nonEmptyDocsList = new ArrayList<>();

        for (QueryResultContainer.SingleRankedResult rankedResults : queryResultContainer.rankedResults) {
            // collect non-empty documents
            if (rankedResults.plainText != null && !rankedResults.plainText.isEmpty()) {
                nonEmptyDocsList.add(rankedResults);
            }
        }

        System.out.println("Non-empty docs coune: " + nonEmptyDocsList.size());

        if (crop) {
            // now cut at 93
            nonEmptyDocsList = nonEmptyDocsList.subList(0, (100 - maxMissing));
            System.out.println("After cropping: " + nonEmptyDocsList.size());
        }
        System.out.println("After cleaning: " + nonEmptyDocsList.size());

        queryResultContainer.rankedResults.clear();
        queryResultContainer.rankedResults.addAll(nonEmptyDocsList);

        // and save the query to output dir
        File outputFile = new File(outputDir, queryResultContainer.qID + ".xml");
        FileUtils.writeStringToFile(outputFile, queryResultContainer.toXML(), "utf-8");
        System.out.println("Finished " + outputFile);
    }

}

From source file:io.mindmaps.migration.csv.Main.java

public static void main(String[] args) {

    String csvFileName = null;/*from  ww  w  .  j  a  v a2s.  c o m*/
    String csvEntityType = null;
    String engineURL = null;
    String graphName = null;

    for (int i = 0; i < args.length; i++) {
        if ("-file".equals(args[i]))
            csvFileName = args[++i];
        else if ("-graph".equals(args[i]))
            graphName = args[++i];
        else if ("-engine".equals(args[i]))
            engineURL = args[++i];
        else if ("-as".equals(args[i])) {
            csvEntityType = args[++i];
        } else if ("csv".equals(args[0])) {
            continue;
        } else
            die("Unknown option " + args[i]);
    }

    if (csvFileName == null) {
        die("Please specify CSV file using the -csv option");
    }
    File csvFile = new File(csvFileName);
    if (!csvFile.exists()) {
        die("Cannot find file: " + csvFileName);
    }
    if (graphName == null) {
        die("Please provide the name of the graph using -graph");
    }
    if (csvEntityType == null) {
        csvEntityType = csvFile.getName().replaceAll("[^A-Za-z0-9]", "_");
    }

    System.out.println("Migrating " + csvFileName + " using MM Engine "
            + (engineURL == null ? "local" : engineURL) + " into graph " + graphName);

    // perform migration
    CSVSchemaMigrator schemaMigrator = new CSVSchemaMigrator();
    CSVDataMigrator dataMigrator = new CSVDataMigrator();

    //
    try {
        MindmapsGraph graph = engineURL == null ? MindmapsClient.getGraph(graphName)
                : MindmapsClient.getGraph(graphName, engineURL);

        Loader loader = engineURL == null ? new BlockingLoader(graphName)
                : new DistributedLoader(graphName, Lists.newArrayList(engineURL));

        CSVParser csvParser = CSVParser.parse(csvFile.toURI().toURL(), StandardCharsets.UTF_8,
                CSVFormat.DEFAULT.withHeader());

        schemaMigrator.graph(graph).configure(csvEntityType, csvParser).migrate(loader);

        System.out.println("Schema migration successful");

        dataMigrator.graph(graph).configure(csvEntityType, csvParser).migrate(loader);

        System.out.println("DataType migration successful");

    } catch (Throwable throwable) {
        throwable.printStackTrace(System.err);
    }

    System.exit(0);
}

From source file:cc.wikitools.lucene.FetchWikipediaArticle.java

@SuppressWarnings("static-access")
public static void main(String[] args) throws Exception {
    Options options = new Options();
    options.addOption(//from w w  w .j  av  a  2s  .  c o  m
            OptionBuilder.withArgName("path").hasArg().withDescription("index location").create(INDEX_OPTION));
    options.addOption(
            OptionBuilder.withArgName("num").hasArg().withDescription("article id").create(ID_OPTION));
    options.addOption(
            OptionBuilder.withArgName("string").hasArg().withDescription("article title").create(TITLE_OPTION));

    CommandLine cmdline = null;
    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(ID_OPTION) || cmdline.hasOption(TITLE_OPTION))
            || !cmdline.hasOption(INDEX_OPTION)) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(FetchWikipediaArticle.class.getName(), options);
        System.exit(-1);
    }

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

    WikipediaSearcher searcher = new WikipediaSearcher(indexLocation);
    PrintStream out = new PrintStream(System.out, true, "UTF-8");

    if (cmdline.hasOption(ID_OPTION)) {
        int id = Integer.parseInt(cmdline.getOptionValue(ID_OPTION));
        Document doc = searcher.getArticle(id);

        if (doc == null) {
            System.err.print("id " + id + " doesn't exist!\n");
        } else {
            out.println(doc.getField(IndexField.TEXT.name).stringValue());
        }
    } else {
        String title = cmdline.getOptionValue(TITLE_OPTION);
        Document doc = searcher.getArticle(title);

        if (doc == null) {
            System.err.print("article \"" + title + "\" doesn't exist!\n");
        } else {
            out.println(doc.getField(IndexField.TEXT.name).stringValue());
        }
    }

    searcher.close();
    out.close();
}

From source file:com.dumontierlab.pdb2rdf.cluster.ClusterServer.java

public static void main(String[] args) {

    Options options = createOptions();// ww w. java  2 s.  com
    CommandLineParser parser = createCliParser();

    try {
        CommandLine cmd = parser.parse(options, args);

        if (!cmd.hasOption("dir")) {
            LOG.fatal("You need to specify the input directory");
            System.exit(1);
        }
        File inputDir = new File(cmd.getOptionValue("dir"));
        if (!inputDir.exists() || !inputDir.isDirectory()) {
            LOG.fatal("The specified input directory is not a valid directory");
            System.exit(1);
        }

        int port = DEFAULT_PORT;
        if (cmd.hasOption("port")) {
            try {
                port = Integer.parseInt(cmd.getOptionValue("port"));
            } catch (NumberFormatException e) {
                LOG.fatal("Invalid port number", e);
                System.exit(1);
            }
        }
        boolean gzip = cmd.hasOption("gzip");

        try {
            startServer(inputDir, gzip, port);
        } catch (Exception e) {
            LOG.fatal("Unable to start the server.", e);
            System.exit(1);
        }

    } catch (ParseException e) {
        LOG.fatal("Unable understand your command.");
        printUsage();
        System.exit(1);
    }

}