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:edu.toronto.cs.xcurator.cli.CLIRunner.java

public static void main(String[] args) {
    Options options = setupOptions();/*w w  w .jav a 2 s.com*/
    CommandLineParser parser = new BasicParser();
    try {
        CommandLine line = parser.parse(options, args);
        if (line.hasOption('t')) {
            fileType = line.getOptionValue('t');
        } else {
            fileType = XML;
        }
        if (line.hasOption('o')) {
            tdbDirectory = line.getOptionValue('o');
            File d = new File(tdbDirectory);
            if (!d.exists() || !d.isDirectory()) {
                throw new Exception("TDB directory does not exist, please create.");
            }
        }
        if (line.hasOption('h')) {
            domain = line.getOptionValue('h');
            try {
                URL url = new URL(domain);
            } catch (MalformedURLException ex) {
                throw new Exception("The domain name is ill-formed");
            }
        } else {
            printHelpAndExit(options);
        }
        if (line.hasOption('m')) {
            serializeMapping = true;
            mappingFilename = line.getOptionValue('m');
        }
        if (line.hasOption('d')) {
            dirLocation = line.getOptionValue('d');
            inputStreams = new ArrayList<>();
            final List<String> files = Util.getFiles(dirLocation);
            for (String inputfile : files) {
                File f = new File(inputfile);
                if (f.isFile() && f.exists()) {
                    System.out.println("Adding document to mapping discoverer: " + inputfile);
                    inputStreams.add(new FileInputStream(f));
                } // If it is a URL download link for the document from SEC
                else if (inputfile.startsWith("http") && inputfile.contains("://")) {
                    // Download
                    System.out.println("Adding remote document to mapping discoverer: " + inputfile);
                    try {
                        URL url = new URL(inputfile);
                        InputStream remoteDocumentStream = url.openStream();
                        inputStreams.add(remoteDocumentStream);
                    } catch (MalformedURLException ex) {
                        throw new Exception("The document URL is ill-formed: " + inputfile);
                    } catch (IOException ex) {
                        throw new Exception("Error in downloading remote document: " + inputfile);
                    }
                } else {
                    throw new Exception("Cannot open XBRL document: " + f.getName());
                }
            }
        }

        if (line.hasOption('f')) {
            fileLocation = line.getOptionValue('f');
            inputStreams = new ArrayList<>();
            File f = new File(fileLocation);
            if (f.isFile() && f.exists()) {
                System.out.println("Adding document to mapping discoverer: " + fileLocation);
                inputStreams.add(new FileInputStream(f));
            } // If it is a URL download link for the document from SEC
            else if (fileLocation.startsWith("http") && fileLocation.contains("://")) {
                // Download
                System.out.println("Adding remote document to mapping discoverer: " + fileLocation);
                try {
                    URL url = new URL(fileLocation);
                    InputStream remoteDocumentStream = url.openStream();
                    inputStreams.add(remoteDocumentStream);
                } catch (MalformedURLException ex) {
                    throw new Exception("The document URL is ill-formed: " + fileLocation);
                } catch (IOException ex) {
                    throw new Exception("Error in downloading remote document: " + fileLocation);
                }
            } else {

                throw new Exception("Cannot open XBRL document: " + f.getName());
            }

        }

        setupDocumentBuilder();
        RdfFactory rdfFactory = new RdfFactory(new RunConfig(domain));
        List<Document> documents = new ArrayList<>();
        for (InputStream inputStream : inputStreams) {
            Document dataDocument = null;
            if (fileType.equals(JSON)) {
                String json = IOUtils.toString(inputStream);
                final String xml = Util.json2xml(json);
                final InputStream xmlInputStream = IOUtils.toInputStream(xml);
                dataDocument = createDocument(xmlInputStream);
            } else {
                dataDocument = createDocument(inputStream);
            }
            documents.add(dataDocument);
        }
        if (serializeMapping) {
            System.out.println("Mapping file will be saved to: " + new File(mappingFilename).getAbsolutePath());
            rdfFactory.createRdfs(documents, tdbDirectory, mappingFilename);
        } else {
            rdfFactory.createRdfs(documents, tdbDirectory);
        }
    } catch (Exception ex) {
        ex.printStackTrace();
        System.err.println("Unexpected exception: " + ex.getMessage());
        System.exit(1);
    }
}

From source file:comparetopics.CompareTwoGroupTopics.java

public static void main(String[] args) {

    Scanner sc = new Scanner(System.in);
    System.out.println("please input the path for File1: ");
    String filepath1 = sc.nextLine();
    System.out.println("please input the path for File2: ");
    String filepath2 = sc.nextLine();

    try {//from w  w  w .  j a  v  a 2  s.  com
        File file1 = new File(filepath1);
        File file2 = new File(filepath2);
        System.out.println("File1: " + filepath1);
        System.out.println("File2: " + filepath2);

        if (!file1.exists()) {
            System.out.println("File1 isn't exist");
        } else if (!file2.exists()) {
            System.out.println("File2 isn't exist");
        } else {
            try (InputStream in1 = new FileInputStream(file1.getPath());
                    BufferedReader reader1 = new BufferedReader(new InputStreamReader(in1))) {

                String line1 = null;
                int lineNr1 = -1;
                while ((line1 = reader1.readLine()) != null) {
                    ++lineNr1;

                    int lineNr2 = -1;
                    String line2 = null;
                    try (InputStream in2 = new FileInputStream(file2.getPath());
                            BufferedReader reader2 = new BufferedReader(new InputStreamReader(in2))) {
                        while ((line2 = reader2.readLine()) != null) {
                            ++lineNr2;
                            compareTwoGroups(line1, line2, lineNr1, lineNr2);
                        }
                    }
                    System.out.println();
                }
            }
        }

    } catch (IOException ex) {
        Logger.getLogger(CompareTopics.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:net.agkn.field_stripe.FileRecordEncoder.java

/**
 * @param  args refer to the {@link FileRecordEncoder class JavaDoc} for the
 *         required parameters. This can never be <code>null</code>.
 */// w  w  w . j av a 2  s .co  m
public static void main(final String[] args) {
    if (args.length != 4) {
        showUsage();
        System.exit(1/*EXIT_FAILURE*/);
        return;
    } /* else -- there are the expected number of arguments */

    // validate all input parameters
    final File idlBasePath = new File(args[0]);
    if (!idlBasePath.exists()) {
        System.err.println("The IDL base path does not exist: " + args[0]);
        System.exit(1/*EXIT_FAILURE*/);
    }
    if (!idlBasePath.isDirectory()) {
        System.err.println("The IDL base path is not a directory: " + args[0]);
        System.exit(1/*EXIT_FAILURE*/);
    }
    final String fqMessageName = args[1];
    final File jsonInputRecord = new File(args[2]);
    if (!jsonInputRecord.exists()) {
        System.err.println("The input JSON record file does not exist: " + args[2]);
        System.exit(1/*EXIT_FAILURE*/);
    }
    if (jsonInputRecord.isDirectory()) {
        System.err.println("The input JSON record is not a file: " + args[2]);
        System.exit(1/*EXIT_FAILURE*/);
    }
    final File outputPath = new File(args[3]);
    if (!outputPath.exists()) {
        System.err.println("The output base path does not exist: " + args[3]);
        System.exit(1/*EXIT_FAILURE*/);
    }
    if (!outputPath.isDirectory()) {
        System.err.println("The output base path is not a directory: " + args[3]);
        System.exit(1/*EXIT_FAILURE*/);
    }

    IFieldStripeWriterFactory fieldStripeWriterFactory = null/*none to start*/;
    try {
        final ICompositeType schema = createSchema(idlBasePath, fqMessageName);
        final IRecordReader recordReader = createRecordReader(jsonInputRecord);
        fieldStripeWriterFactory = createFieldStripeWriterFactory(outputPath);
        final RootFieldStripeEncoder rootEncoder = createEncoderTree(schema, fieldStripeWriterFactory);

        // encode each record
        while (rootEncoder.encode(recordReader))
            ;
    } catch (final OperationFailedException ofe) {
        System.err.println(
                "An error occurred while encoding records into field-stripes: " + ofe.getLocalizedMessage());
        System.exit(1/*EXIT_FAILURE*/);
    } finally {
        try {
            if (fieldStripeWriterFactory != null)
                fieldStripeWriterFactory.closeAllWriters();
        } catch (final OperationFailedException ofe) {
            System.err.println(
                    "An error occurred while closing field-stripe writers: " + ofe.getLocalizedMessage());
            System.exit(1/*EXIT_FAILURE*/);
        }
    }

    System.exit(0/*EXIT_SUCCESS*/);
}

From source file:eu.annocultor.utils.XmlUtils.java

public static void main(String... args) throws Exception {
    // Handling command line parameters with Apache Commons CLI
    Options options = new Options();

    options.addOption(OptionBuilder.withArgName(OPT_FN).hasArg().isRequired()
            .withDescription("XML file name to be pretty-printed").create(OPT_FN));

    // now lets parse the input
    CommandLineParser parser = new BasicParser();
    CommandLine cmd;/*www .  j a  v  a2s. co  m*/
    try {
        cmd = parser.parse(options, Utils.getCommandLineFromANNOCULTOR_ARGS(args));
    } catch (ParseException pe) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("pretty", options);
        return;
    }

    List<File> files = Utils.expandFileTemplateFrom(new File("."), cmd.getOptionValue(OPT_FN));
    for (File file : files) {
        // XML pretty print
        System.out.println("Pretty-print for file " + file);
        if (file.exists())
            prettyPrintXmlFileSAX(file.getCanonicalPath());
        else
            throw new Exception("File not found: " + file.getCanonicalPath());
    }
}

From source file:Inmemantlr.java

public static void main(String[] args) {
    LOGGER.info("Inmemantlr tool");

    HelpFormatter hformatter = new HelpFormatter();

    Options options = new Options();

    // Binary arguments
    options.addOption("h", "print this message");

    Option grmr = Option.builder().longOpt("grmrfiles").hasArgs().desc("comma-separated list of ANTLR files")
            .required(true).argName("grmrfiles").type(String.class).valueSeparator(',').build();

    Option infiles = Option.builder().longOpt("infiles").hasArgs()
            .desc("comma-separated list of files to parse").required(true).argName("infiles").type(String.class)
            .valueSeparator(',').build();

    Option utilfiles = Option.builder().longOpt("utilfiles").hasArgs()
            .desc("comma-separated list of utility files to be added for " + "compilation").required(false)
            .argName("utilfiles").type(String.class).valueSeparator(',').build();

    Option odir = Option.builder().longOpt("outdir")
            .desc("output directory in which the dot files will be " + "created").required(false).hasArg(true)
            .argName("outdir").type(String.class).build();

    options.addOption(infiles);/*from w  w  w. ja  v a2 s  . c o  m*/
    options.addOption(grmr);
    options.addOption(utilfiles);
    options.addOption(odir);

    CommandLineParser parser = new DefaultParser();

    CommandLine cmd = null;

    try {
        cmd = parser.parse(options, args);
        if (cmd.hasOption('h')) {
            hformatter.printHelp("java -jar inmemantlr.jar", options);
            System.exit(0);
        }
    } catch (ParseException e) {
        hformatter.printHelp("java -jar inmemantlr.jar", options);
        LOGGER.error(e.getMessage());
        System.exit(-1);
    }

    // input files
    Set<File> ins = getFilesForOption(cmd, "infiles");
    // grammar files
    Set<File> gs = getFilesForOption(cmd, "grmrfiles");
    // utility files
    Set<File> uf = getFilesForOption(cmd, "utilfiles");
    // output dir
    Set<File> od = getFilesForOption(cmd, "outdir");

    if (od.size() > 1) {
        LOGGER.error("output directories must be less than or equal to 1");
        System.exit(-1);
    }

    if (ins.size() <= 0) {
        LOGGER.error("no input files were specified");
        System.exit(-1);
    }

    if (gs.size() <= 0) {
        LOGGER.error("no grammar files were specified");
        System.exit(-1);
    }

    LOGGER.info("create generic parser");
    GenericParser gp = null;
    try {
        gp = new GenericParser(gs.toArray(new File[gs.size()]));
    } catch (FileNotFoundException e) {
        LOGGER.error(e.getMessage());
        System.exit(-1);
    }

    if (!uf.isEmpty()) {
        try {
            gp.addUtilityJavaFiles(uf.toArray(new String[uf.size()]));
        } catch (FileNotFoundException e) {
            LOGGER.error(e.getMessage());
            System.exit(-1);
        }
    }

    LOGGER.info("create and add parse tree listener");
    DefaultTreeListener dt = new DefaultTreeListener();
    gp.setListener(dt);

    LOGGER.info("compile generic parser");
    try {
        gp.compile();
    } catch (CompilationException e) {
        LOGGER.error("cannot compile generic parser: {}", e.getMessage());
        System.exit(-1);
    }

    String fpfx = "";
    for (File of : od) {
        if (!of.exists() || !of.isDirectory()) {
            LOGGER.error("output directory does not exist or is not a " + "directory");
            System.exit(-1);
        }
        fpfx = of.getAbsolutePath();
    }

    Ast ast;
    for (File f : ins) {
        try {
            gp.parse(f);
        } catch (IllegalWorkflowException | FileNotFoundException e) {
            LOGGER.error(e.getMessage());
            System.exit(-1);
        }
        ast = dt.getAst();

        if (!fpfx.isEmpty()) {
            String of = fpfx + "/" + FilenameUtils.removeExtension(f.getName()) + ".dot";

            LOGGER.info("write file {}", of);

            try {
                FileUtils.writeStringToFile(new File(of), ast.toDot(), "UTF-8");
            } catch (IOException e) {
                LOGGER.error(e.getMessage());
                System.exit(-1);
            }
        } else {
            LOGGER.info("Tree for {} \n {}", f.getName(), ast.toDot());
        }
    }

    System.exit(0);
}

From source file:com.act.biointerpretation.sars.SeqDBReactionGrouper.java

public static void main(String[] args) throws Exception {
    // Build command line parser.
    Options opts = new Options();
    for (Option.Builder b : OPTION_BUILDERS) {
        opts.addOption(b.build());//  www  .j  av a  2s .  c om
    }

    CommandLine cl = null;
    try {
        CommandLineParser parser = new DefaultParser();
        cl = parser.parse(opts, args);
    } catch (ParseException e) {
        LOGGER.error("Argument parsing failed: %s", e.getMessage());
        HELP_FORMATTER.printHelp(SeqDBReactionGrouper.class.getCanonicalName(), HELP_MESSAGE, opts, null, true);
        System.exit(1);
    }

    // Print help.
    if (cl.hasOption(OPTION_HELP)) {
        HELP_FORMATTER.printHelp(SeqDBReactionGrouper.class.getCanonicalName(), HELP_MESSAGE, opts, null, true);
        return;
    }

    // Handle arguments
    String mongoDBName = cl.getOptionValue(OPTION_DB);
    MongoDB mongoDB = new MongoDB(LOCAL_HOST, MONGO_PORT, mongoDBName);

    File outputFile = new File(cl.getOptionValue(OPTION_OUTPUT_PATH));
    if (outputFile.isDirectory() || outputFile.exists()) {
        LOGGER.error("Supplied output file is a directory or already exists.");
        System.exit(1);
    }
    outputFile.createNewFile();

    Integer limit = DEFAULT_LIMIT_INFINITY;
    if (cl.hasOption(OPTION_LIMIT)) {
        limit = Integer.parseInt(cl.getOptionValue(OPTION_LIMIT));
    }
    LOGGER.info("Only processing first %d entries in Seq DB.", limit);

    SeqDBReactionGrouper enzymeGrouper = new SeqDBReactionGrouper(mongoDB.getSeqIterator(), mongoDBName, limit);

    LOGGER.info("Scanning seq db for reactions with same seq.");
    ReactionGroupCorpus groupCorpus = enzymeGrouper.getReactionGroupCorpus();

    LOGGER.info("Writing output to file.");
    groupCorpus.printToJsonFile(outputFile);

    LOGGER.info("Complete!");
}

From source file:net.myrrix.online.eval.ParameterOptimizer.java

public static void main(String[] args) throws Exception {
    if (args.length < 4) {
        System.err.println(/*from  w w  w  .  j a  v a  2  s  .c o  m*/
                "Usage: dataDirectory numSteps evaluationPercentage property=min:max [property2=min2:max2 ...]");
        return;
    }

    final File dataDir = new File(args[0]);
    Preconditions.checkArgument(dataDir.exists() && dataDir.isDirectory(), "Not a directory: %s", dataDir);
    Preconditions.checkArgument(dataDir.listFiles().length > 0, "No files in: %s", dataDir);
    int numSteps = Integer.parseInt(args[1]);
    Preconditions.checkArgument(numSteps >= 2, "# steps must be at least 2: %s", numSteps);
    final double evaluationPercentage = Double.parseDouble(args[2]);
    Preconditions.checkArgument(evaluationPercentage > 0.0 && evaluationPercentage <= 1.0,
            "evaluationPercentage must be in (0,1]: %s", evaluationPercentage);

    Map<String, ParameterRange> parameterRanges = Maps.newHashMapWithExpectedSize(args.length);
    for (int i = 3; i < args.length; i++) {
        String[] propValue = EQUALS.split(args[i]);
        String systemProperty = propValue[0];
        String[] minMax = COLON.split(propValue[1]);
        ParameterRange range;
        try {
            int min = Integer.parseInt(minMax[0]);
            int max = Integer.parseInt(minMax.length == 1 ? minMax[0] : minMax[1]);
            range = new ParameterRange(min, max);
        } catch (NumberFormatException ignored) {
            double min = Double.parseDouble(minMax[0]);
            double max = Double.parseDouble(minMax.length == 1 ? minMax[0] : minMax[1]);
            range = new ParameterRange(min, max);
        }
        parameterRanges.put(systemProperty, range);
    }

    Callable<Number> evaluator = new Callable<Number>() {
        @Override
        public Number call() throws IOException, TasteException, InterruptedException {
            MyrrixIRStatistics stats = (MyrrixIRStatistics) new PrecisionRecallEvaluator().evaluate(dataDir,
                    0.9, evaluationPercentage, null);
            return stats == null ? null : stats.getMeanAveragePrecision();
        }
    };

    ParameterOptimizer optimizer = new ParameterOptimizer(parameterRanges, numSteps, evaluator, false);
    Map<String, Number> optimalValues = optimizer.findGoodParameterValues();
    System.out.println(optimalValues);
}

From source file:com.moss.appkeep.server.AppkeepServer.java

public static void main(String[] args) throws Exception {
    System.setProperty("org.mortbay.log.class", Slf4jLog.class.getName());

    File log4jConfigFile = new File("log4j.xml");

    if (log4jConfigFile.exists()) {
        DOMConfigurator.configureAndWatch(log4jConfigFile.getAbsolutePath(), 1000);
    } else {//from   w  w w .jav a 2  s . c o m
        BasicConfigurator.configure();
        Logger.getRootLogger().setLevel(Level.INFO);
    }

    ServerConfiguration config;

    JAXBContext context = JAXBContext.newInstance(ServerConfiguration.class,

            VeracityId.class, SimpleId.class,

            PasswordProofRecipie.class, ProofDelegationRecipie.class);

    JAXBHelper helper = new JAXBHelper(context);

    Logger log = Logger.getLogger(AppkeepServer.class);

    File configFile = new File("settings.xml");
    if (!configFile.exists())
        configFile = new File(new File(System.getProperty("user.dir")), ".appkeep-server.xml");
    if (!configFile.exists())
        configFile = new File("/etc/appkeep-server.xml");

    if (!configFile.exists()) {
        config = new ServerConfiguration();
        helper.writeToFile(helper.writeToXmlString(config), configFile);
        log.warn("Created default config file at " + configFile.getAbsolutePath());
    } else {
        log.info("Reading configuration from " + configFile.getAbsolutePath());
        config = helper.readFromFile(configFile);
    }

    ProxyFactory proxyFactory = new ProxyFactory(new HessianProxyProvider());
    try {
        new AppkeepServer(config, proxyFactory);
    } catch (Exception e) {
        e.printStackTrace();
        System.out.println("Unexpected Error.  Shutting Down.");
        System.exit(1);
    }
}

From source file:com.ibm.jaql.MiniCluster.java

/**
 * @param args/*ww  w. ja  v  a2s. c  o m*/
 */
public static void main(String[] args) throws IOException {
    String clusterHome = System.getProperty("hadoop.minicluster.dir");
    if (clusterHome == null) {
        clusterHome = "./minicluster";
        System.setProperty("hadoop.minicluster.dir", clusterHome);
    }
    LOG.info("hadoop.minicluster.dir=" + clusterHome);
    File clusterFile = new File(clusterHome);
    if (!clusterFile.exists()) {
        clusterFile.mkdirs();
    }
    if (!clusterFile.isDirectory()) {
        throw new IOException("minicluster home directory must be a directory: " + clusterHome);
    }
    if (!clusterFile.canRead() || !clusterFile.canWrite()) {
        throw new IOException("minicluster home directory must be readable and writable: " + clusterHome);
    }

    String logDir = System.getProperty("hadoop.log.dir");
    if (logDir == null) {
        logDir = clusterHome + File.separator + "logs";
        System.setProperty("hadoop.log.dir", logDir);
    }
    File logFile = new File(logDir);
    if (!logFile.exists()) {
        logFile.mkdirs();
    }

    String confDir = System.getProperty("hadoop.conf.override");
    if (confDir == null) {
        confDir = clusterHome + File.separator + "conf";
        System.setProperty("hadoop.conf.override", confDir);
    }
    File confFile = new File(confDir);
    if (!confFile.exists()) {
        confFile.mkdirs();
    }

    System.out.println("starting minicluster in " + clusterHome);
    MiniCluster mc = new MiniCluster(args);
    // To find the ports in the 
    // hdfs: search for: Web-server up at: localhost:####
    // mapred: search for: mapred.JobTracker: JobTracker webserver: ####
    Configuration conf = mc.getConf();
    System.out.println("fs.default.name: " + conf.get("fs.default.name"));
    System.out.println("dfs.http.address: " + conf.get("dfs.http.address"));
    System.out.println("mapred.job.tracker.http.address: " + conf.get("mapred.job.tracker.http.address"));

    boolean waitForInterrupt;
    try {
        System.out.println("press enter to end minicluster (or eof to run forever)...");
        waitForInterrupt = System.in.read() < 0; // wait for any input or eof
    } catch (Exception e) {
        // something odd happened.  Just shutdown. 
        LOG.error("error reading from stdin", e);
        waitForInterrupt = false;
    }

    // eof means that we will wait for a kill signal
    while (waitForInterrupt) {
        System.out.println("minicluster is running until interrupted...");
        try {
            Thread.sleep(60 * 60 * 1000);
        } catch (InterruptedException e) {
            waitForInterrupt = false;
        }
    }

    System.out.println("shutting down minicluster...");
    try {
        mc.tearDown();
    } catch (Exception e) {
        LOG.error("error while shutting down minicluster", e);
    }
}

From source file:D20140128.ApacheXMLGraphicsTest.TilingPatternExample.java

/**
 * Command-line interface//  w  ww .j  a va2s . c o m
 * @param args command-line arguments
 */
public static void main(String[] args) {
    try {
        File targetDir;
        if (args.length >= 1) {
            targetDir = new File(args[0]);
        } else {
            targetDir = new File(".");
        }
        if (!targetDir.exists()) {
            System.err.println("Target Directory does not exist: " + targetDir);
        }
        File outputFile = new File(targetDir, "tiling-example.ps");
        File pngFile = new File(targetDir, "tiling-example.png");
        TilingPatternExample app = new TilingPatternExample();
        app.generatePSusingJava2D(outputFile);
        System.out.println("File written: " + outputFile.getCanonicalPath());
        app.generatePNGusingJava2D(pngFile);
        System.out.println("File written: " + pngFile.getCanonicalPath());
    } catch (Exception e) {
        e.printStackTrace();
    }
}