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.axiomine.largecollections.generator.GeneratorKryoKPrimitiveValue.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 a  v a 2s.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 VPACKAGE = args[2];
    //Class name (no packages) of the Key class Ex. String
    //Class name (no packages) of the value class Ex. Integer
    String V = 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 vCls = V;

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

    String CLASS_NAME = "KryoK" + vCls + "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/KryoKeyPrimitiveValueMapTemplate.java"));
        program = program.replaceAll("#MY_PACKAGE#", MY_PACKAGE);
        program = program.replaceAll("#CUSTOM_IMPORTS#", importStr);

        program = program.replaceAll("#CLASS_NAME#", CLASS_NAME);
        program = program.replaceAll("#V#", V);
        program = program.replaceAll("#VPACKAGE#", VPACKAGE);

        program = program.replaceAll("#VCLS#", vCls);
        System.out.println(outFile.getAbsolutePath());
        FileUtils.writeStringToFile(outFile, program);
    }
}

From source file:net.skyebook.zerocollada.ZeroCollada.java

/**
 * @param args//from w  w  w .  jav a  2 s  .c o m
 * @throws ParseException 
 * @throws IOException 
 * @throws JDOMException 
 */
public static void main(String[] args) throws ParseException, JDOMException, IOException {
    // Setup Apache Commons CLI
    optionsSetup();

    CommandLineParser parser = new PosixParser();
    CommandLine cmd = parser.parse(options, args);

    if (args.length == 0 || cmd.hasOption(ZCOpts.help)) {
        showHelp();
    }

    // was there a valid operation specified?
    if (hasValidOption(cmd)) {
        File fileFromCommandLine = new File(args[args.length - 1]);
        if (!fileFromCommandLine.exists()) {
            System.err.println(
                    "The file located at " + fileFromCommandLine.toString() + " does not exist!  Qutting.");
            return;
        } else if (fileFromCommandLine.isFile() && fileFromCommandLine.toString().endsWith(".dae")) {
            // we've been given a single file.  Act on this single file
            doRequestedAction(fileFromCommandLine, cmd);
        } else if (fileFromCommandLine.isDirectory()) {
            // We've been given a directory of files process the ones that are .dae
            for (File file : fileFromCommandLine.listFiles()) {
                if (file.isFile() && file.toString().endsWith(".dae")) {
                    doRequestedAction(file, cmd);
                } else {
                    System.err.println(file.toString() + " does not seem to be a COLLADA file");
                }
            }
        }
    } else {
        // Then why are we here?
        if (cmd.hasOption(ZCOpts.includeY)) {
            System.err.println(
                    "You have used the " + ZCOpts.includeY + " option but have not asked for a transform (t)");
        } else if (cmd.hasOption(ZCOpts.anchorCenter)) {
            System.err.println(
                    "You have used the " + ZCOpts.includeY + " option but have not asked for a transform (t)");
        }
    }

}

From source file:com.adobe.aem.demomachine.Updates.java

public static void main(String[] args) {

    String rootFolder = null;/*w  ww.j  av  a 2s  . co m*/

    // Command line options for this tool
    Options options = new Options();
    options.addOption("f", true, "Demo Machine root folder");
    CommandLineParser parser = new BasicParser();
    try {
        CommandLine cmd = parser.parse(options, args);

        if (cmd.hasOption("f")) {
            rootFolder = cmd.getOptionValue("f");
        }

    } catch (Exception e) {
        System.exit(-1);
    }

    Properties md5properties = new Properties();

    try {
        URL url = new URL(
                "https://raw.githubusercontent.com/Adobe-Marketing-Cloud/aem-demo-machine/master/conf/checksums.properties");
        InputStream in = url.openStream();
        Reader reader = new InputStreamReader(in, "UTF-8");
        md5properties.load(reader);
        reader.close();
    } catch (Exception e) {
        System.out.println("Error: Cannot connect to GitHub.com to check for updates");
        System.exit(-1);
    }

    System.out.println(AemDemoConstants.HR);

    int nbUpdateAvailable = 0;

    List<String[]> listPaths = Arrays.asList(AemDemoConstants.demoPaths);
    for (String[] path : listPaths) {
        if (path.length == 5) {
            logger.debug(path[1]);
            File pathFolder = new File(rootFolder + (path[1].length() > 0 ? (File.separator + path[1]) : ""));
            if (pathFolder.exists()) {
                String newMd5 = AemDemoUtils.calcMD5HashForDir(pathFolder, Boolean.parseBoolean(path[3]),
                        false);
                logger.debug("MD5 is: " + newMd5);
                String oldMd5 = md5properties.getProperty("demo.md5." + path[0]);
                if (oldMd5 == null || oldMd5.length() == 0) {
                    logger.error("Cannot find MD5 for " + path[0]);
                    System.out.println(path[2] + " : Cannot find M5 checksum");
                    continue;
                }
                if (newMd5.equals(oldMd5)) {
                    continue;
                } else {
                    System.out.println(path[2] + " : New update available"
                            + (path[0].equals("0") ? " (use 'git pull' to get the latest changes)" : ""));
                    nbUpdateAvailable++;
                }
            } else {
                System.out.println(path[2] + " : Not installed");
            }
        }
    }

    if (nbUpdateAvailable == 0) {
        System.out.println("Your AEM Demo Machine is up to date!");
    }

    System.out.println(AemDemoConstants.HR);

}

From source file:alluxio.master.backcompat.BackwardsCompatibilityJournalGenerator.java

/**
 * Generates journal files to be used by the backwards compatibility test. The files are named
 * based on the current version defined in ProjectConstants.VERSION. Run this with each release,
 * and commit the created journal and snapshot into the git repository.
 *
 * @param args no args expected//from ww w .  j  a  va2 s  . c  o  m
 */
public static void main(String[] args) throws Exception {
    BackwardsCompatibilityJournalGenerator generator = new BackwardsCompatibilityJournalGenerator();
    new JCommander(generator, args);
    if (!LoginUser.get().getName().equals("root")) {
        System.err.printf("Journals must be generated as root so that they can be replayed by root%n");
        System.exit(-1);
    }
    File journalDst = new File(generator.getOutputDirectory(),
            String.format("journal-%s", ProjectConstants.VERSION));
    if (journalDst.exists()) {
        System.err.printf("%s already exists, delete it first%n", journalDst.getAbsolutePath());
        System.exit(-1);
    }
    File backupDst = new File(generator.getOutputDirectory(),
            String.format("backup-%s", ProjectConstants.VERSION));
    if (backupDst.exists()) {
        System.err.printf("%s already exists, delete it first%n", backupDst.getAbsolutePath());
        System.exit(-1);
    }
    MultiProcessCluster cluster = MultiProcessCluster.newBuilder(PortCoordination.BACKWARDS_COMPATIBILITY)
            .setClusterName("BackwardsCompatibility").setNumMasters(1).setNumWorkers(1).build();
    try {
        cluster.start();
        cluster.notifySuccess();
        cluster.waitForAllNodesRegistered(10 * Constants.SECOND_MS);
        for (TestOp op : OPS) {
            op.apply(cluster.getClients());
        }
        AlluxioURI backup = cluster.getMetaMasterClient()
                .backup(new File(generator.getOutputDirectory()).getAbsolutePath(), true).getBackupUri();
        FileUtils.moveFile(new File(backup.getPath()), backupDst);
        cluster.stopMasters();
        FileUtils.copyDirectory(new File(cluster.getJournalDir()), journalDst);
    } catch (Throwable t) {
        t.printStackTrace();
    } finally {
        cluster.destroy();
    }
    System.out.printf("Artifacts successfully generated at %s and %s%n", journalDst.getAbsolutePath(),
            backupDst.getAbsolutePath());
}

From source file:com.doculibre.constellio.utils.resources.WriteResourceBundleUtils.java

@SuppressWarnings("unchecked")
public static void main(String[] args) throws Exception {
    File binDir = ClasspathUtils.getClassesDir();
    File projectDir = binDir.getParentFile();
    File sourceDir = new File(projectDir, "source");

    String defaultLanguage;//w w w .j a va2 s  .  c o  m
    String otherLanguage;
    if (args.length > 0) {
        defaultLanguage = args[0];
        otherLanguage = args[1];
    } else {
        defaultLanguage = Locale.ENGLISH.getLanguage();
        otherLanguage = Locale.FRENCH.getLanguage();
    }

    List<File> propertiesFiles = (List<File>) FileUtils.listFiles(sourceDir, new String[] { "properties" },
            true);
    for (File propertiesFile : propertiesFiles) {
        File propertiesDir = propertiesFile.getParentFile();

        String propertiesNameWoutSuffix = StringUtils.substringBefore(propertiesFile.getName(), "_");
        propertiesNameWoutSuffix = StringUtils.substringBefore(propertiesNameWoutSuffix, ".properties");

        String noLanguageFileName = propertiesNameWoutSuffix + ".properties";
        String defaultLanguageFileName = propertiesNameWoutSuffix + "_" + defaultLanguage + ".properties";
        String otherLanguageFileName = propertiesNameWoutSuffix + "_" + otherLanguage + ".properties";

        File noLanguageFile = new File(propertiesDir, noLanguageFileName);
        File defaultLanguageFile = new File(propertiesDir, defaultLanguageFileName);
        File otherLanguageFile = new File(propertiesDir, otherLanguageFileName);

        if (defaultLanguageFile.exists() && otherLanguageFile.exists() && !noLanguageFile.exists()) {
            System.out.println(defaultLanguageFile.getPath() + " > " + noLanguageFileName);
            System.out.println(defaultLanguageFile.getPath() + " > empty file");

            defaultLanguageFile.renameTo(noLanguageFile);
            FileWriter defaultLanguageEmptyFileWriter = new FileWriter(defaultLanguageFile);
            defaultLanguageEmptyFileWriter.write("");
            IOUtils.closeQuietly(defaultLanguageEmptyFileWriter);
        }
    }
}

From source file:eu.digitisation.idiomaident.utils.CorpusFilter.java

public static void main(String args[]) {
    if (args.length < 2) {
        System.err.println("Usage: CorpusFilter" + "inFolder outFolder");
    } else {//from  www  .j a v  a  2 s  .c o  m
        File inFile = new File(args[0]);
        File outFile = new File(args[1]);

        if (inFile.exists() && inFile.isDirectory()) {
            if (!outFile.exists()) {
                outFile.mkdir();
            }

            CorpusFilter.filter(inFile, outFile, "es");
        }
    }
}

From source file:grnet.filter.XMLFiltering.java

public static void main(String[] args) throws IOException {
    // TODO Auto-generated method ssstub

    Enviroment enviroment = new Enviroment(args[0]);

    if (enviroment.envCreation) {
        Core core = new Core();

        XMLSource source = new XMLSource(args[0]);

        File sourceFile = source.getSource();

        if (sourceFile.exists()) {

            Collection<File> xmls = source.getXMLs();

            System.out.println("Filtering repository:" + enviroment.dataProviderFilteredIn.getName());

            System.out.println("Number of files to filter:" + xmls.size());

            Iterator<File> iterator = xmls.iterator();

            FilteringReport report = null;
            if (enviroment.getArguments().getProps().getProperty(Constants.createReport)
                    .equalsIgnoreCase("true")) {
                report = new FilteringReport(enviroment.getArguments().getDestFolderLocation(),
                        enviroment.getDataProviderFilteredIn().getName());
            }/*from  ww  w.ja  v a  2  s .c o  m*/

            ConnectionFactory factory = new ConnectionFactory();
            factory.setHost(enviroment.getArguments().getQueueHost());
            factory.setUsername(enviroment.getArguments().getQueueUserName());
            factory.setPassword(enviroment.getArguments().getQueuePassword());

            while (iterator.hasNext()) {

                StringBuffer logString = new StringBuffer();
                logString.append(enviroment.dataProviderFilteredIn.getName());
                File xmlFile = iterator.next();

                String name = xmlFile.getName();
                name = name.substring(0, name.indexOf(".xml"));
                logString.append(" " + name);

                boolean xmlIsFilteredIn = core.filterXML(xmlFile, enviroment.getArguments().getQueries());

                if (xmlIsFilteredIn) {
                    logString.append(" " + "FilteredIn");
                    slf4jLogger.info(logString.toString());

                    Connection connection = factory.newConnection();
                    Channel channel = connection.createChannel();
                    channel.queueDeclare(QUEUE_NAME, false, false, false, null);

                    channel.basicPublish("", QUEUE_NAME, null, logString.toString().getBytes());
                    channel.close();
                    connection.close();

                    try {
                        if (report != null) {
                            report.appendXMLFileNameNStatus(xmlFile.getPath(), Constants.filteredInData);
                            report.raiseFilteredInFilesNum();
                        }

                        FileUtils.copyFileToDirectory(xmlFile, enviroment.getDataProviderFilteredIn());
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        // e.printStackTrace();
                        e.printStackTrace();
                        System.out.println("Filtering failed.");
                    }
                } else {
                    logString.append(" " + "FilteredOut");
                    slf4jLogger.info(logString.toString());

                    Connection connection = factory.newConnection();
                    Channel channel = connection.createChannel();
                    channel.queueDeclare(QUEUE_NAME, false, false, false, null);

                    channel.basicPublish("", QUEUE_NAME, null, logString.toString().getBytes());
                    channel.close();
                    connection.close();
                    try {
                        if (report != null) {
                            report.appendXMLFileNameNStatus(xmlFile.getPath(), Constants.filteredOutData);
                            report.raiseFilteredOutFilesNum();
                        }
                        FileUtils.copyFileToDirectory(xmlFile, enviroment.getDataProviderFilteredOuT());
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        // e.printStackTrace();
                        e.printStackTrace();
                        System.out.println("Filtering failed.");
                    }
                }
            }
            if (report != null) {

                report.appendXPathExpression(enviroment.getArguments().getQueries());

                report.appendGeneralInfo();
            }
            System.out.println("Filtering is done.");
        }

    }
}

From source file:de.cwclan.cwsa.serverendpoint.main.ServerEndpoint.java

/**
 * @param args the command line arguments
 *//*  w ww . jav  a 2 s.c  om*/
public static void main(String[] args) {
    Options options = new Options();
    options.addOption(OptionBuilder.withArgName("file").hasArg().withDescription(
            "Used to enter path of configfile. Default file is endpoint.properties. NOTE: If the file is empty or does not exsist, a default config is created.")
            .create("config"));
    options.addOption("h", "help", false, "displays this page");
    CommandLineParser parser = new PosixParser();
    Properties properties = new Properties();
    try {
        /*
         * parse default config shipped with jar
         */
        CommandLine cmd = parser.parse(options, args);

        /*
         * load default configuration
         */
        InputStream in = ServerEndpoint.class.getResourceAsStream("/endpoint.properties");
        if (in == null) {
            throw new IOException("Unable to load default config from JAR. This should not happen.");
        }
        properties.load(in);
        in.close();
        log.debug("Loaded default config base: {}", properties.toString());
        if (cmd.hasOption("help")) {
            printHelp(options);
            System.exit(0);
        }

        /*
         * parse cutom config if exists, otherwise create default cfg
         */
        if (cmd.hasOption("config")) {
            File file = new File(cmd.getOptionValue("config", "endpoint.properties"));
            if (file.exists() && file.canRead() && file.isFile()) {
                in = new FileInputStream(file);
                properties.load(in);
                log.debug("Loaded custom config from {}: {}", file.getAbsoluteFile(), properties);
            } else {
                log.warn("Config file does not exsist. A default file will be created.");
            }
            FileWriter out = new FileWriter(file);
            properties.store(out,
                    "Warning, this file is recreated on every startup to merge missing parameters.");
        }

        /*
         * create and start endpoint
         */
        log.info("Config read successfull. Values are: {}", properties);
        ServerEndpoint endpoint = new ServerEndpoint(properties);
        Runtime.getRuntime().addShutdownHook(endpoint.getShutdownHook());
        endpoint.start();
    } catch (IOException ex) {
        log.error("Error while reading config.", ex);
    } catch (ParseException ex) {
        log.error("Error while parsing commandline options: {}", ex.getMessage());
        printHelp(options);
        System.exit(1);
    }
}

From source file:com.act.lcms.v2.TraceIndexAnalyzer.java

public static void main(String[] args) throws Exception {
    Options opts = new Options();
    for (Option.Builder b : OPTION_BUILDERS) {
        opts.addOption(b.build());/*w  w  w. j a  v a2 s. c  o m*/
    }

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

    if (cl.hasOption("help")) {
        HELP_FORMATTER.printHelp(TraceIndexExtractor.class.getCanonicalName(), HELP_MESSAGE, opts, null, true);
        return;
    }

    File rocksDBFile = new File(cl.getOptionValue(OPTION_INDEX_PATH));
    if (!rocksDBFile.exists()) {
        System.err.format("Index file at %s does not exist, nothing to analyze", rocksDBFile.getAbsolutePath());
        HELP_FORMATTER.printHelp(TraceIndexExtractor.class.getCanonicalName(), HELP_MESSAGE, opts, null, true);
        System.exit(1);
    }

    LOGGER.info("Starting analysis");

    TraceIndexAnalyzer analyzer = new TraceIndexAnalyzer();
    analyzer.runExtraction(rocksDBFile, new File(cl.getOptionValue(OPTION_OUTPUT_PATH)));

    LOGGER.info("Done");
}

From source file:jvmoptions.OptionAnalyzer.java

public static void main(String[] args) throws Exception {
    File f = new File("result");
    if (f.exists() == false && f.mkdirs() == false) {
        System.exit(1);//from   w  w w.j a  va  2s  . com
    }
    Path json = toJson("java6", "java7", "java8");
    toCSV(json);
}