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:com.asksunny.tool.RemoteDataStreamer.java

/**
 * @param args/*from   w w w .  j  a  v a 2  s  . co m*/
 */
public static void main(String[] args) throws Exception {
    RemoteDataStreamer streamer = new RemoteDataStreamer();
    Options options = CLIOptionAnnotationBasedBinder.getOptions(streamer);
    CLIOptionAnnotationBasedBinder.bindPosix(options, args, streamer);

    if (streamer.isHelp() || streamer.isVersion() || streamer.getFilePath() == null) {
        HelpFormatter hfmt = new HelpFormatter();
        if (streamer.isHelp()) {
            hfmt.printHelp(streamer.getClass().getName() + " <options>", options);
            System.exit(0);
        } else if (streamer.isVersion()) {
            System.out.println(VERSION);
            System.exit(0);
        } else {
            hfmt.printHelp(streamer.getClass().getName() + " <options>", options);
            System.exit(1);
        }
    }
    File f = new File(streamer.getFilePath());
    boolean sender = f.exists() && f.isFile();
    if (sender && streamer.getHost() == null) {
        System.err.println("Host option is required for sender");
        HelpFormatter hfmt = new HelpFormatter();
        hfmt.printHelp(streamer.getClass().getName() + " <options>", options);
        System.exit(1);
    }

    if (sender && streamer.isCompress()) {
        streamer.sendCompress();
    } else if (sender && !streamer.isCompress()) {
        streamer.send();
    } else if (!sender && streamer.isCompress()) {
        streamer.receiveCompress();
    } else {
        streamer.receive();
    }

    System.out.printf("File %s transfer complete.", streamer.getFilePath());

}

From source file:boa.datagen.BoaGenerator.java

public static void main(final String[] args) throws IOException {
    final Options options = new Options();
    BoaGenerator.addOptions(options);/*  w  ww.  ja  v  a 2  s .  c  om*/

    final CommandLine cl;
    try {
        cl = new PosixParser().parse(options, args);
        BoaGenerator.handleCmdOptions(cl, options, args);
    } catch (final Exception e) {
        printHelp(options, e.getMessage());
        return;
    }

    /*
     * 1. if user provides local json files 2. if user provides username and
     * password in both the cases json files are going to be available
     */

    if (jsonAvailable) {
        CacheGithubJSON.main(args);
        try {
            SeqRepoImporter.main(args);
        } catch (final InterruptedException e) {
            e.printStackTrace();
        }

        // SeqProjectCombiner.main(args);
        // SeqSort.main(args);
        // SeqSortMerge.main(args);
        try {
            MapFileGen.main(args);
        } catch (final Exception e) {
            e.printStackTrace();
        }
    } else { // when user provides local repo and does not have json files
        final File output = new File(DefaultProperties.GH_JSON_CACHE_PATH);
        if (!output.exists())
            output.mkdirs();
        LocalGitSequenceGenerator.localGitSequenceGenerate(DefaultProperties.GH_GIT_PATH,
                DefaultProperties.GH_JSON_CACHE_PATH);
        try {
            MapFileGen.main(args);
        } catch (final Exception e) {
            e.printStackTrace();
        }
    }
    if (cl.hasOption("cache"))
        clear(true);
    else
        clear(false);
}

From source file:edu.ucsb.cs.eager.sa.cerebro.Cerebro.java

public static void main(String[] args) {
    Options options = new Options();
    options.addOption("ccp", "cerebro-classpath", true, "Cerebro classpath");
    options.addOption("c", "class", true, "Class to be used as the starting point");
    options.addOption("dnc", "disable-nec-classes", false, "Disable loading of necessary classes");
    options.addOption("wp", "whole-program", false, "Enable whole program mode");

    CommandLine cmd;/*from  w  w  w .  j a  v a  2 s.  co  m*/
    try {
        CommandLineParser parser = new BasicParser();
        cmd = parser.parse(options, args);
    } catch (ParseException e) {
        System.err.println("Error: " + e.getMessage() + "\n");
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("Cerebro", options);
        return;
    }

    String classPath = cmd.getOptionValue("ccp");
    if (classPath == null) {
        System.err.println("Cerebro classpath (ccp) option is required");
        return;
    } else {
        String[] paths = classPath.split(":");
        for (String p : paths) {
            File file = new File(p);
            if (!file.exists()) {
                System.err.println("Path segment: " + p + " mentioned in classpath does not exist");
                return;
            }
        }
    }

    String startingPoint = cmd.getOptionValue("c");
    if (startingPoint == null) {
        System.err.println("Starting point class (c) option is required");
        return;
    }

    Cerebro cerebro = new Cerebro(classPath, startingPoint);
    cerebro.setLoadNecessaryClasses(!cmd.hasOption("dnc"));
    cerebro.setWholeProgramMode(cmd.hasOption("wp"));
    cerebro.setVerbose(true);
    cerebro.analyze();
}

From source file:com.gordcorp.jira2db.App.java

public static void main(String[] args) throws Exception {
    File log4jFile = new File("log4j.xml");
    if (log4jFile.exists()) {
        DOMConfigurator.configure("log4j.xml");
    }/*  w w  w  . j a  v a2  s  .  com*/

    Option help = new Option("h", "help", false, "print this message");

    @SuppressWarnings("static-access")
    Option project = OptionBuilder.withLongOpt("project").withDescription("Only sync Jira project PROJECT")
            .hasArg().withArgName("PROJECT").create();

    @SuppressWarnings("static-access")
    Option property = OptionBuilder.withArgName("property=value").hasArgs(2).withValueSeparator()
            .withDescription("use value for given property").create("D");

    @SuppressWarnings("static-access")
    Option testJira = OptionBuilder.withLongOpt("test-jira")
            .withDescription("Test the connection to Jira and print the results").create();

    @SuppressWarnings("static-access")
    Option forever = OptionBuilder.withLongOpt("forever")
            .withDescription("Will continue polling Jira and syncing forever").create();

    Options options = new Options();
    options.addOption(help);
    options.addOption(project);
    options.addOption(property);
    options.addOption(testJira);
    options.addOption(forever);

    CommandLineParser parser = new GnuParser();
    try {

        CommandLine line = parser.parse(options, args);

        if (line.hasOption(help.getOpt())) {
            printHelp(options);
            return;
        }

        // Overwrite the properties file with command line arguments
        if (line.hasOption("D")) {
            String[] values = line.getOptionValues("D");
            for (int i = 0; i < values.length; i = i + 2) {
                String key = values[i];
                // If user does not provide a value for this property, use
                // an empty string
                String value = "";
                if (i + 1 < values.length) {
                    value = values[i + 1];
                }

                log.info("Setting key=" + key + " value=" + value);
                PropertiesWrapper.set(key, value);
            }

        }

        if (line.hasOption("test-jira")) {
            testJira();
        } else {
            JiraSynchroniser jira = new JiraSynchroniser();

            if (line.hasOption("project")) {

                jira.setProjects(Arrays.asList(new String[] { line.getOptionValue("project") }));
            }

            if (line.hasOption("forever")) {
                jira.syncForever();
            } else {
                jira.syncAll();
            }
        }
    } catch (ParseException exp) {

        log.error("Parsing failed: " + exp.getMessage());
    } catch (Exception e) {
        log.error(e.getMessage(), e);
    }
}

From source file:DIA_Umpire_To_Skyline.DIA_Umpire_To_Skyline.java

/**
 * @param args the command line arguments
 *//*w w w.  ja v a 2 s  .  c o  m*/
public static void main(String[] args) throws FileNotFoundException, IOException, Exception {
    System.out.println(
            "=================================================================================================");
    System.out.println("DIA-Umpire_To_Skyline (version: " + UmpireInfo.GetInstance().Version + ")");
    if (args.length < 1) {
        System.out.println(
                "command format error, it should be like: java -jar -Xmx20G DIA_Umpire_To_Skyline.jar Path NoThreads");
        System.out.println("command : java -jar -Xmx20G DIA_Umpire_To_Skyline.jar Path [Option]\n");
        System.out.println("\nOptions");
        System.out.println("\t-t\tNo. of threads, Ex: -t4 (using four threads, default value)");
        System.out.println(
                "\t-cP\tPath of msconvert.exe for mzXML conversion, Ex: -cP (using four threads, default value)");
        return;
    }
    try {
        ConsoleLogger.SetConsoleLogger(Level.DEBUG);
        ConsoleLogger.SetFileLogger(Level.DEBUG,
                FilenameUtils.getFullPath(args[0]) + "diaumpire_to_skyline.log");
    } catch (Exception e) {
        System.out.println("Logger initialization failed");
    }

    Logger.getRootLogger().info("Path:" + args[0]);
    String msconvertpath = "C:/inetpub/tpp-bin/msconvert";

    String WorkFolder = args[0];
    int NoCPUs = 4;

    for (int i = 1; i < args.length; i++) {
        if (args[i].startsWith("-")) {
            if (args[i].startsWith("-cP")) {
                msconvertpath = args[i].substring(3);
                Logger.getRootLogger().info("MSConvert path: " + msconvertpath);
            }
            if (args[i].startsWith("-t")) {
                NoCPUs = Integer.parseInt(args[i].substring(2));
                Logger.getRootLogger().info("No. of threads: " + NoCPUs);
            }
        }
    }

    HashMap<String, File> AssignFiles = new HashMap<>();

    try {
        File folder = new File(WorkFolder);
        if (!folder.exists()) {
            Logger.getRootLogger().info("Path: " + folder.getAbsolutePath() + " cannot be found.");
        }
        for (final File fileEntry : folder.listFiles()) {
            if (fileEntry.isFile() && fileEntry.getAbsolutePath().toLowerCase().endsWith(".mzxml")
                    && !fileEntry.getAbsolutePath().toLowerCase().endsWith("q1.mzxml")
                    && !fileEntry.getAbsolutePath().toLowerCase().endsWith("q2.mzxml")
                    && !fileEntry.getAbsolutePath().toLowerCase().endsWith("q3.mzxml")) {
                AssignFiles.put(fileEntry.getAbsolutePath(), fileEntry);
            }
            if (fileEntry.isDirectory()) {
                for (final File fileEntry2 : fileEntry.listFiles()) {
                    if (fileEntry2.isFile() && fileEntry2.getAbsolutePath().toLowerCase().endsWith(".mzxml")
                            && !fileEntry2.getAbsolutePath().toLowerCase().endsWith("q1.mzxml")
                            && !fileEntry2.getAbsolutePath().toLowerCase().endsWith("q2.mzxml")
                            && !fileEntry2.getAbsolutePath().toLowerCase().endsWith("q3.mzxml")) {
                        AssignFiles.put(fileEntry2.getAbsolutePath(), fileEntry2);
                    }
                }
            }
        }

        Logger.getRootLogger().info("No. of files assigned :" + AssignFiles.size());
        for (File fileEntry : AssignFiles.values()) {
            Logger.getRootLogger().info(fileEntry.getAbsolutePath());
        }

        ExecutorService executorPool = null;
        executorPool = Executors.newFixedThreadPool(3);

        for (File fileEntry : AssignFiles.values()) {
            String mzXMLFile = fileEntry.getAbsolutePath();
            FileThread thread = new FileThread(mzXMLFile, NoCPUs, msconvertpath);
            executorPool.execute(thread);
        }
        executorPool.shutdown();
        try {
            executorPool.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
        } catch (InterruptedException e) {
            Logger.getRootLogger().info("interrupted..");
        }
    } catch (Exception e) {
        Logger.getRootLogger().error(e.getMessage());
        throw e;
    }
    Logger.getRootLogger().info("Job done");
    Logger.getRootLogger().info(
            "=================================================================================================");

}

From source file:com.linkedin.helix.mock.relay.DummyRelayProcess.java

public static void main(String[] args) throws Exception {
    String zkConnectString = "pganti-md:2181";
    String clusterName = "SDR_RELAY";
    String instanceName = "ela4-rly02.prod.linkedin.com_10015";
    String file = null;/*  ww  w  . jav a 2s  .  c om*/

    if (args.length > 0) {
        CommandLine cmd = processCommandLineArgs(args);
        zkConnectString = cmd.getOptionValue(zkServer);
        clusterName = cmd.getOptionValue(cluster);

        String host = cmd.getOptionValue(hostAddress);
        String portString = cmd.getOptionValue(hostPort);
        int port = Integer.parseInt(portString);
        instanceName = host + "_" + port;

        file = cmd.getOptionValue(configFile);
        if (file != null) {
            File f = new File(file);
            if (!f.exists()) {
                System.err.println("static config file doesn't exist");
                System.exit(1);
            }
        }

    }
    // Espresso_driver.py will consume this
    System.out.println("Dummy process started");

    DummyRelayProcess process = new DummyRelayProcess(zkConnectString, clusterName, instanceName, file);

    process.start();
    Thread.currentThread().join();
}

From source file:ASCII2NATIVE.java

public static void main(String[] args) {
    File f = new File("c:\\mydb.script");
    File f2 = new File("c:\\mydb3.script");
    if (f.exists() && f.isFile()) {
        // convert param-file
        BufferedReader br = null;
        StringBuffer sb = new StringBuffer();
        String line;/*from   w ww . j a v a2s.  com*/

        try {
            br = new BufferedReader(new InputStreamReader(new FileInputStream(f), "JISAutoDetect"));

            while ((line = br.readLine()) != null) {
                System.out.println(ascii2Native(line));
                sb.append(ascii2Native(line)).append(";\n");//.append(";\n\r")
            }

            BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(f2), "utf-8"));
            out.append(sb.toString());
            out.flush();
            out.close();
        } catch (FileNotFoundException e) {
            System.err.println("file not found - " + f);
        } catch (IOException e) {
            System.err.println("read error - " + f);
        } finally {
            try {
                if (br != null)
                    br.close();
            } catch (Exception e) {
            }
        }
    } else {
        // // convert param-data
        // System.out.print(ascii2native(args[i]));
        // if (i + 1 < args.length)
        // System.out.print(' ');
    }
}

From source file:com.axiomine.largecollections.generator.GeneratorPrimitiveKeyKryoValue.java

public static void main(String[] args) throws Exception {
    //Package of the new class you are generating Ex. com.mypackage
    String MY_PACKAGE = args[0];//from  w ww.  j av a  2 s  . c o m
    //Any custom imports you need (: seperated). Use - if no custom imports are included
    //Ex. java.util.*:java.lang.Random     
    String CUSTOM_IMPORTS = args[1].equals("-") ? "" : args[1];
    //Package of your Key serializer class. Use com.axiomine.bigcollections.functions
    //Package of your value serializer class. Use com.axiomine.bigcollections.functions
    String KPACKAGE = args[2];
    //Class name (no packages) of the Key class Ex. String
    //Class name (no packages) of the value class Ex. Integer
    String K = args[3];
    //Specify if you are using a KryoTemplate to generate your classes
    //If true the template used to generate the class is KryoBasedMapTemplte, if false the JavaLangBasedMapTemplate is used
    //You can customize the name of the class generated
    String kCls = K;

    if (kCls.equals("byte[]")) {
        kCls = "BytesArray";
    }

    String CLASS_NAME = kCls + "KryoV" + "Map"; //Default

    //String templatePath = args[5];
    File root = new File("");
    File outFile = new File(root.getAbsolutePath() + "/src/main/java/" + MY_PACKAGE.replaceAll("\\.", "/") + "/"
            + CLASS_NAME + ".java");

    if (outFile.exists()) {
        System.out.println(outFile.getAbsolutePath() + " already exists. Please delete it and try again");
    }
    {
        String[] imports = null;
        String importStr = "";

        if (!StringUtils.isBlank(CUSTOM_IMPORTS)) {
            CUSTOM_IMPORTS.split(":");
            for (String s : imports) {
                importStr = "import " + s + ";\n";
            }
        }
        String program = FileUtils.readFileToString(
                new File(root.getAbsolutePath() + "/src/main/resources/PrimitiveKeyKryoValueMapTemplate.java"));
        program = program.replaceAll("#MY_PACKAGE#", MY_PACKAGE);
        program = program.replaceAll("#CUSTOM_IMPORTS#", importStr);

        program = program.replaceAll("#CLASS_NAME#", CLASS_NAME);
        program = program.replaceAll("#K#", K);
        program = program.replaceAll("#KCLS#", kCls);
        program = program.replaceAll("#KPACKAGE#", KPACKAGE);
        System.out.println(outFile.getAbsolutePath());
        FileUtils.writeStringToFile(outFile, program);
    }
}

From source file:com.soulgalore.velocity.MergeXMLWithVelocity.java

/**
 * Merge a xml file with Velocity template. The third parameter is the properties file, where the
 * key/value is added to the velocity context. The fourth parameter is the output file. If not
 * included, the result is printed to system.out.
 * /*from  w ww.java2 s  .  co  m*/
 * @param args are file.xml template.vm properties.prop [output.file]
 * @throws JDOMException if the xml file couldn't be parsed
 * @throws IOException couldn't find one of the files
 */
public static void main(String[] args) throws JDOMException, IOException {

    if (args.length < 3) {
        System.out.println(
                "Missing input files. XMLToVelocity file.xml template.vm prop.properties [output.file]");
        return;
    }

    final Properties properties = new Properties();
    final File prop = new File(args[2]);

    if (prop.exists())
        properties.load(new FileReader(prop));
    else
        throw new IOException("Couldn't find the property file:" + prop.getAbsolutePath());

    final MergeXMLWithVelocity xtv = new MergeXMLWithVelocity(properties);
    xtv.create(args);
}

From source file:com.opensearchserver.affinities.Main.java

public static void main(String[] args) throws IOException, ParseException {
    Logger.getLogger("").setLevel(Level.WARNING);
    Options options = new Options();
    options.addOption("h", "help", false, "print this message");
    options.addOption("d", "datadir", true, "Data directory");
    options.addOption("p", "port", true, "TCP port");
    CommandLineParser parser = new GnuParser();
    CommandLine cmd = parser.parse(options, args);
    if (cmd.hasOption("help")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("java -jar target/oss-affinities.jar", options);
        return;/* w w w .  j a v  a 2s  .  c  o m*/
    }
    int port = cmd.hasOption("p") ? Integer.parseInt(cmd.getOptionValue("p")) : 9092;

    File dataDir = new File(System.getProperty("user.home"), "opensearchserver_affinities");
    if (cmd.hasOption("d"))
        dataDir = new File(cmd.getOptionValue("d"));
    if (!dataDir.exists())
        throw new IOException("The data directory does not exists: " + dataDir);
    if (!dataDir.isDirectory())
        throw new IOException("The data directory path is not a directory: " + dataDir);
    AffinityList.load(dataDir);

    UndertowJaxrsServer server = new UndertowJaxrsServer()
            .start(Undertow.builder().addHttpListener(port, "0.0.0.0"));
    server.deploy(Main.class);
}