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:eu.annocultor.converters.geonames.GeonamesDumpToRdf.java

public static void main(String[] args) throws Exception {
    File root = new File("input_source");

    // load country-continent match
    countryToContinent//w  w  w . ja  v a  2 s  .c  o m
            .load((new GeonamesDumpToRdf()).getClass().getResourceAsStream("/country-to-continent.properties"));

    // creating files
    Map<String, BufferedWriter> files = new HashMap<String, BufferedWriter>();
    Map<String, Boolean> started = new HashMap<String, Boolean>();

    for (Object string : countryToContinent.keySet()) {
        String continent = countryToContinent.getProperty(string.toString());
        File dir = new File(root, continent);
        if (!dir.exists()) {
            dir.mkdir();
        }
        files.put(string.toString(), new BufferedWriter(new OutputStreamWriter(
                new FileOutputStream(new File(root, continent + "/" + string + ".rdf")), "UTF-8")));
        System.out.println(continent + "/" + string + ".rdf");
        started.put(string.toString(), false);
    }

    System.out.println(started);

    Pattern countryPattern = Pattern
            .compile("<inCountry rdf\\:resource\\=\"http\\://www\\.geonames\\.org/countries/\\#(\\w\\w)\"/>");
    long counter = 0;
    LineIterator it = FileUtils.lineIterator(new File(root, "all-geonames-rdf.txt"), "UTF-8");
    try {
        while (it.hasNext()) {
            String text = it.nextLine();
            if (text.startsWith("http://sws.geonames"))
                continue;

            // progress
            counter++;
            if (counter % 100000 == 0) {
                System.out.print("*");
            }
            //         System.out.println(counter);
            // get country
            String country = null;
            Matcher matcher = countryPattern.matcher(text);
            if (matcher.find()) {
                country = matcher.group(1);
            }
            //         System.out.println(country);
            if (country == null)
                country = "null";
            text = text.replace("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?><rdf:RDF",
                    "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><rdf:RDF");
            if (started.get(country) == null)
                throw new Exception("Unknow country " + country);
            if (started.get(country).booleanValue()) {
                // remove RDF opening
                text = text.substring(text.indexOf("<rdf:RDF "));
                text = text.substring(text.indexOf(">") + 1);
            }
            // remove RDF ending
            text = text.substring(0, text.indexOf("</rdf:RDF>"));
            files.get(country).append(text + "\n");
            if (!started.get(country).booleanValue()) {
                // System.out.println("Started with country " + country);
            }
            started.put(country, true);
        }
    } finally {
        LineIterator.closeQuietly(it);
    }

    for (Object string : countryToContinent.keySet()) {
        boolean hasStarted = started.get(string.toString()).booleanValue();
        if (hasStarted) {
            BufferedWriter bf = files.get(string.toString());
            bf.append("</rdf:RDF>");
            bf.flush();
            bf.close();
        }
    }
    return;
}

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

@SuppressWarnings("static-access")
public static void main(String[] args) throws Exception {
    Options options = new Options();
    options.addOption(/*from   w  w w . ja va  2s  .  co  m*/
            OptionBuilder.withArgName("path").hasArg().withDescription("index location").create(INDEX_OPTION));
    options.addOption(
            OptionBuilder.withArgName("string").hasArg().withDescription("query text").create(QUERY_OPTION));
    options.addOption(OptionBuilder.withArgName("num").hasArg().withDescription("number of results to return")
            .create(NUM_RESULTS_OPTION));

    options.addOption(new Option(VERBOSE_OPTION, "print out complete document"));
    options.addOption(new Option(TITLE_OPTION, "search title"));
    options.addOption(new Option(ARTICLE_OPTION, "search article"));

    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(QUERY_OPTION) || !cmdline.hasOption(INDEX_OPTION)
            || !cmdline.hasOption(QUERY_OPTION)) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(SearchWikipedia.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);
    int numResults = cmdline.hasOption(NUM_RESULTS_OPTION)
            ? Integer.parseInt(cmdline.getOptionValue(NUM_RESULTS_OPTION))
            : DEFAULT_NUM_RESULTS;
    boolean verbose = cmdline.hasOption(VERBOSE_OPTION);
    boolean searchArticle = !cmdline.hasOption(TITLE_OPTION);

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

    WikipediaSearcher searcher = new WikipediaSearcher(indexLocation);
    TopDocs rs = null;
    if (searchArticle) {
        rs = searcher.searchArticle(queryText, numResults);
    } else {
        rs = searcher.searchTitle(queryText, numResults);
    }

    int i = 1;
    for (ScoreDoc scoreDoc : rs.scoreDocs) {
        Document hit = searcher.doc(scoreDoc.doc);

        out.println(String.format("%d. %s (wiki id = %s, lucene id = %d) %f", i,
                hit.getField(IndexField.TITLE.name).stringValue(),
                hit.getField(IndexField.ID.name).stringValue(), scoreDoc.doc, scoreDoc.score));
        if (verbose) {
            out.println("# " + hit.toString().replaceAll("[\\n\\r]+", " "));
        }
        i++;
    }

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

From source file:copi.ScalaEntryPoint.java

public static void main(String[] args) {
    /*/*from  www.  ja  v  a  2s.  c  o m*/
       * Set lwjgl library path so that LWJGL finds the natives depending on
       * the OS.
       */
    File libDir = new File(path);

    if (!libDir.exists()) {
        // create native lib folder 
        libDir.mkdir();

        // retrieve os type
        String osName = System.getProperty("os.name");

        // try to determine if the system is 64 bit  
        boolean is64bit = false;
        if (System.getProperty("os.name").contains("Windows")) {
            is64bit = (System.getenv("ProgramFiles(x86)") != null);
        } else {
            is64bit = (System.getProperty("os.arch").indexOf("64") != -1);
        }

        // construct name of native lib file 
        String natLibLWJGL = "";
        if (osName.startsWith("Windows")) {
            natLibLWJGL += "lwjgl";
            if (is64bit)
                natLibLWJGL += "64";
            natLibLWJGL += ".dll";
        } else if (osName.startsWith("Linux")) {
            natLibLWJGL += "liblwjgl";
            if (is64bit)
                natLibLWJGL += "64";
            natLibLWJGL += ".so";
        } else if (osName.startsWith("Mac OS X")) {
            natLibLWJGL += "liblwjgl";
            natLibLWJGL += ".jnilib";
        } else {
            System.out.println("Unsupported OS: " + osName + ". Exiting.");
            System.exit(-1);
        }

        // try to establish an input stream on the native lib inside the jar
        InputStream fis = ScalaEntryPoint.class.getResourceAsStream("/" + natLibLWJGL);
        if (fis == null) {
            System.out.println("Native library file " + natLibLWJGL + " was not found inside JAR.");
            System.exit(-1);
        }

        // establish an output stream on the target file 
        File fOut = new File(path + "/" + natLibLWJGL);
        try (FileOutputStream fos = new FileOutputStream(fOut)) {
            // create file at destination if not already existing
            if (!fOut.exists())
                fOut.createNewFile();

            // making buffer for copy operation 
            byte[] buffer = new byte[1024];
            int readBytes;

            // Open output stream and copy data between source file in JAR and the temporary file
            try {
                while ((readBytes = fis.read(buffer)) != -1) {
                    fos.write(buffer, 0, readBytes);
                }
            } finally {
                fos.close();
                fis.close();
            }
        } catch (IOException e) {
            System.out.println(e.getMessage());
            System.exit(-1);
        }

        // register shutdown hook
        JVMShutdownHook jvmShutdownHook = new JVMShutdownHook();
        Runtime.getRuntime().addShutdownHook(jvmShutdownHook);

    }

    // set lwjgl native library path
    System.setProperty("org.lwjgl.librarypath", libDir.getAbsolutePath());

    // start COPI
    System.out.println("Starting COPI ...");
    (new SICApplicationLogic()).render();
}

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

public static void main(String[] args) throws IOException {
    // queries with narratives in CSV
    File queries = new File(args[0]);
    File relevantInformationExamplesFile = new File(args[1]);

    Map<Integer, Map<Integer, List<String>>> relevantInformationMap = parseRelevantInformationFile(
            relevantInformationExamplesFile);

    // output dir
    File outputDir = new File(args[2]);
    if (!outputDir.exists()) {
        outputDir.mkdirs();/*from   w  ww .  j a v  a2 s  . c om*/
    }

    // iterate over queries
    CSVParser csvParser = CSVParser.parse(queries, Charset.forName("utf-8"), CSVFormat.DEFAULT);
    for (CSVRecord record : csvParser) {
        // create new container, fill, and store
        QueryResultContainer container = new QueryResultContainer();
        container.qID = record.get(0);
        container.query = record.get(1);

        // Fill some dummy text first
        container.relevantInformationExamples.addAll(Collections.singletonList("ERROR. Information missing."));
        container.irrelevantInformationExamples
                .addAll(Collections.singletonList("ERROR. Information missing."));

        // and now fill it with existing information if available
        Integer queryID = Integer.valueOf(container.qID);
        if (relevantInformationMap.containsKey(queryID)) {
            if (relevantInformationMap.get(queryID).containsKey(0)) {
                container.irrelevantInformationExamples = new ArrayList<>(
                        relevantInformationMap.get(queryID).get(0));
            }

            if (relevantInformationMap.get(queryID).containsKey(1)) {
                container.relevantInformationExamples = new ArrayList<>(
                        relevantInformationMap.get(queryID).get(1));
            }
        }

        File outputFile = new File(outputDir, container.qID + ".xml");
        FileUtils.writeStringToFile(outputFile, container.toXML());
        System.out.println("Finished " + outputFile);
    }
}

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

public static void main(String args[]) {
    if (args.length < 3) {
        System.err.println("Usage: ExtractTextSamples " + "numSamples inFolder outCsvText");
    } else {/*  w ww .  j a  va 2  s  .  c o m*/
        int numSamples = Integer.parseInt(args[0]);
        File inFolder = new File(args[1]);
        File outFile = new File(args[2]);

        if (inFolder.exists() && inFolder.isDirectory()) {
            extractSamples(numSamples, inFolder, outFile);
        }
    }
}

From source file:edu.vt.middleware.cas.ldap.LoadDriver.java

public static void main(final String[] args) {
    if (args.length < 4) {
        System.out.println("USAGE: LoadDriver sample_count thread_count "
                + "path/to/credentials.csv path/to/spring-context.xml");
        return;//from w ww .  j  ava 2  s  . c  om
    }
    final int samples = Integer.parseInt(args[0]);
    final int threads = Integer.parseInt(args[1]);
    final File credentials = new File(args[2]);
    if (!credentials.exists()) {
        throw new IllegalArgumentException(credentials + " does not exist.");
    }
    ApplicationContext context;
    try {
        context = new ClassPathXmlApplicationContext(args[3]);
    } catch (BeanDefinitionStoreException e) {
        if (e.getCause() instanceof FileNotFoundException) {
            // Try treating path as filesystem path
            context = new FileSystemXmlApplicationContext(args[3]);
        } else {
            throw e;
        }
    }
    final LoadDriver driver = new LoadDriver(samples, threads, credentials, context);
    System.err.println("Load test configuration:");
    System.err.println("\tthreads: " + threads);
    System.err.println("\tsamples: " + samples);
    System.err.println("\tcredentials: " + credentials);
    driver.start();
    while (driver.getState().hasWorkRemaining()) {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
        }
    }
    driver.stop();
}

From source file:de.tudarmstadt.ukp.experiments.argumentation.convincingness.sampling.Step2ArgumentPairsSampling.java

public static void main(String[] args) throws Exception {
    String inputDir = args[0];/*from w  w w  .  j  av a 2  s  .  c o  m*/

    // /tmp
    File outputDir = new File(args[1]);
    if (!outputDir.exists()) {
        outputDir.mkdirs();
    }

    // pseudo-random
    final Random random = new Random(1);

    int totalPairsCount = 0;

    // read all debates
    for (File file : IOHelper.listXmlFiles(new File(inputDir))) {
        Debate debate = DebateSerializer.deserializeFromXML(FileUtils.readFileToString(file, "utf-8"));

        // get two stances
        SortedSet<String> originalStances = debate.getStances();

        // cleaning: some debate has three or more stances (data are inconsistent)
        // remove those with only one argument
        SortedSet<String> stances = new TreeSet<>();
        for (String stance : originalStances) {
            if (debate.getArgumentsForStance(stance).size() > 1) {
                stances.add(stance);
            }
        }

        if (stances.size() != 2) {
            throw new IllegalStateException(
                    "2 stances per debate expected, was " + stances.size() + ", " + stances);
        }

        // for each stance, get pseudo-random N arguments
        for (String stance : stances) {
            List<Argument> argumentsForStance = debate.getArgumentsForStance(stance);

            // shuffle
            Collections.shuffle(argumentsForStance, random);

            // and get max first N arguments
            List<Argument> selectedArguments = argumentsForStance.subList(0,
                    argumentsForStance.size() < MAX_SELECTED_ARGUMENTS_PRO_SIDE ? argumentsForStance.size()
                            : MAX_SELECTED_ARGUMENTS_PRO_SIDE);

            List<ArgumentPair> argumentPairs = new ArrayList<>();

            // now create pairs
            for (int i = 0; i < selectedArguments.size(); i++) {
                for (int j = (i + 1); j < selectedArguments.size(); j++) {
                    Argument arg1 = selectedArguments.get(i);
                    Argument arg2 = selectedArguments.get(j);

                    ArgumentPair argumentPair = new ArgumentPair();
                    argumentPair.setDebateMetaData(debate.getDebateMetaData());

                    // assign arg1 and arg2 pseudo-randomly
                    // (not to have the same argument as arg1 all the time)
                    if (random.nextBoolean()) {
                        argumentPair.setArg1(arg1);
                        argumentPair.setArg2(arg2);
                    } else {
                        argumentPair.setArg1(arg2);
                        argumentPair.setArg2(arg1);
                    }

                    // set unique id
                    argumentPair.setId(argumentPair.getArg1().getId() + "_" + argumentPair.getArg2().getId());

                    argumentPairs.add(argumentPair);
                }
            }

            String fileName = IOHelper.createFileName(debate.getDebateMetaData(), stance);

            File outputFile = new File(outputDir, fileName);

            // and save all sampled pairs into a XML file
            XStreamTools.toXML(argumentPairs, outputFile);

            System.out.println("Saved " + argumentPairs.size() + " pairs to " + outputFile);

            totalPairsCount += argumentPairs.size();
        }

    }

    System.out.println("Total pairs generated: " + totalPairsCount);
}

From source file:br.com.thiagomoreira.bancodobrasil.Main.java

/**
 * @param args//www  .j  a va 2  s.c o m
 */
public static void main(String[] args) throws Exception {
    if (args != null) {
        NumberFormat formatter = NumberFormat.getNumberInstance(new Locale("pt", "BR"));

        formatter.setMaximumFractionDigits(2);
        formatter.setMinimumFractionDigits(2);

        double total = 0;

        for (String arg : args) {
            File input = new File(arg);
            if (input.exists()) {
                List<String> lines = IOUtils.readLines(new FileInputStream(input), "ISO-8859-1");

                Parser parser = new DefaultParser();

                List<Transaction> transactions = parser.parse(lines);

                TransactionList transactionList = new TransactionList();
                transactionList.setStart(parser.getStartDate());
                transactionList.setEnd(parser.getEndDate());
                transactionList.setTransactions(transactions);

                CreditCardAccountDetails creditCardAccountDetails = new CreditCardAccountDetails();
                creditCardAccountDetails.setAccountNumber("7616-3");
                creditCardAccountDetails.setAccountKey(parser.getAccountKey());

                CreditCardStatementResponse creditCardStatementResponse = new CreditCardStatementResponse();
                creditCardStatementResponse.setAccount(creditCardAccountDetails);
                creditCardStatementResponse.setCurrencyCode("BRL");
                creditCardStatementResponse.setTransactionList(transactionList);

                Status status = new Status();
                status.setCode(Status.KnownCode.SUCCESS);
                status.setSeverity(Status.Severity.INFO);

                CreditCardStatementResponseTransaction statementResponse = new CreditCardStatementResponseTransaction();
                statementResponse.setClientCookie(UUID.randomUUID().toString());
                statementResponse.setStatus(status);
                statementResponse.setUID(UUID.randomUUID().toString());
                statementResponse.setMessage(creditCardStatementResponse);

                CreditCardResponseMessageSet creditCardResponseMessageSet = new CreditCardResponseMessageSet();
                creditCardResponseMessageSet.setStatementResponse(statementResponse);

                SortedSet<ResponseMessageSet> messageSets = new TreeSet<ResponseMessageSet>();
                messageSets.add(creditCardResponseMessageSet);

                ResponseEnvelope envelope = new ResponseEnvelope();
                envelope.setUID(UUID.randomUUID().toString());
                envelope.setSecurity(ApplicationSecurity.NONE);
                envelope.setMessageSets(messageSets);

                double brazilianRealsamount = parser.getBrazilianRealsAmount();
                double dolarsAmount = parser.getDolarsAmount();
                double cardTotal = dolarsAmount * parser.getExchangeRate() + brazilianRealsamount;
                total += cardTotal;

                System.out.println(creditCardAccountDetails.getAccountKey());
                System.out.println("TOTAL EM RS " + formatter.format(brazilianRealsamount));
                System.out.println("TOTAL EM US " + formatter.format(dolarsAmount));
                System.out.println("TOTAL FATURA EM RS " + formatter.format(cardTotal));
                System.out.println();

                if (!transactions.isEmpty()) {
                    String parent = System.getProperty("user.home") + "/Downloads";
                    String fileName = arg.replace(".txt", ".ofx");
                    File output = new File(parent, fileName);
                    FileOutputStream fos = new FileOutputStream(output);

                    OFXV1Writer writer = new OFXV1Writer(fos);
                    writer.setWriteAttributesOnNewLine(true);

                    AggregateMarshaller marshaller = new AggregateMarshaller();
                    marshaller.setConversion(new MyFinanceStringConversion());
                    marshaller.marshal(envelope, writer);

                    writer.flush();
                    writer.close();
                }
            }
        }
        System.out.println("TOTAL FATURAS EM RS " + formatter.format(total));
    }

}

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

public static void main(String[] args) {

    String rootFolder = null;/*from w  w  w .  ja v a2 s  .  c  om*/

    // 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();
    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 md5 = AemDemoUtils.calcMD5HashForDir(pathFolder, Boolean.parseBoolean(path[3]), false);
                logger.debug("MD5 is: " + md5);
                md5properties.setProperty("demo.path." + path[0], path[1]);
                md5properties.setProperty("demo.md5." + path[0], md5);
            } else {
                logger.error("Folder cannot be found");
            }
        }
    }

    File md5 = new File(rootFolder + File.separator + "conf" + File.separator + "checksums.properties");
    try {

        @SuppressWarnings("serial")
        Properties tmpProperties = new Properties() {
            @Override
            public synchronized Enumeration<Object> keys() {
                return Collections.enumeration(new TreeSet<Object>(super.keySet()));
            }
        };
        tmpProperties.putAll(md5properties);
        tmpProperties.store(new FileOutputStream(md5), null);
    } catch (Exception e) {
        logger.error(e.getMessage());
    }

    System.out.println("MD5 checkums generated");

}

From source file:fi.helsinki.cs.iot.kahvihub.KahviHub.java

public static void main(String[] args) throws InterruptedException {
    // create Options object
    Options options = new Options();
    // add conf file option
    options.addOption("c", true, "config file");
    CommandLineParser parser = new BasicParser();
    CommandLine cmd;/*from ww w . ja  va2s  . c  om*/
    try {
        cmd = parser.parse(options, args);
        String configFile = cmd.getOptionValue("c");
        if (configFile == null) {
            Log.e(TAG, "The config file option was not provided");
            // automatically generate the help statement
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("d", options);
            System.exit(-1);
        } else {
            try {
                HubConfig hubConfig = ConfigurationFileParser.parseConfigurationFile(configFile);
                Path libdir = Paths.get(hubConfig.getLibdir());
                if (hubConfig.isDebugMode()) {
                    File dir = libdir.toFile();
                    if (dir.exists() && dir.isDirectory())
                        for (File file : dir.listFiles())
                            file.delete();
                }
                final IotHubHTTPD server = new IotHubHTTPD(hubConfig.getPort(), libdir, hubConfig.getHost());
                init(hubConfig);
                try {
                    server.start();
                } catch (IOException ioe) {
                    Log.e(TAG, "Couldn't start server:\n" + ioe);
                    System.exit(-1);
                }
                Runtime.getRuntime().addShutdownHook(new Thread() {
                    @Override
                    public void run() {
                        server.stop();
                        Log.i(TAG, "Server stopped");
                    }
                });

                while (true) {
                    Thread.sleep(1000);
                }
            } catch (ConfigurationParsingException | IOException e) {
                System.out.println("1:" + e.getMessage());
                Log.e(TAG, e.getMessage());
                System.exit(-1);
            }
        }

    } catch (ParseException e) {
        System.out.println(e.getMessage());
        Log.e(TAG, e.getMessage());
        System.exit(-1);
    }
}