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.newproject.ApacheHttp.java

public static void main(String[] args) throws Exception {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    String jsonFilePath = "/Users/vikasmohandoss/Documents/Cloud/test.txt";
    String url = "http://www.sentiment140.com/api/bulkClassifyJson&appid=vm2446@columbia.edu";
    JSONParser jsonParser = new JSONParser();
    JSONObject jsonObject = new JSONObject();
    URL obj = new URL(url);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();
    try {//  w  ww.j av  a2 s  .com
        FileReader fileReader = new FileReader(jsonFilePath);
        jsonObject = (JSONObject) jsonParser.parse(fileReader);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ParseException e) {
        e.printStackTrace();
    }
    System.out.println(jsonObject.toString());
    /*try {
    /*HttpGet httpGet = new HttpGet("http://httpbin.org/get");
    CloseableHttpResponse response1 = httpclient.execute(httpGet);
    // The underlying HTTP connection is still held by the response object
    // to allow the response content to be streamed directly from the network socket.
    // In order to ensure correct deallocation of system resources
    // the user MUST call CloseableHttpResponse#close() from a finally clause.
    // Please note that if response content is not fully consumed the underlying
    // connection cannot be safely re-used and will be shut down and discarded
    // by the connection manager.
    try {
        System.out.println(response1.getStatusLine());
        HttpEntity entity1 = response1.getEntity();
        // do something useful with the response body
        // and ensure it is fully consumed
        EntityUtils.consume(entity1);
    } finally {
        response1.close();
    }
    HttpPost httpPost = new HttpPost("http://httpbin.org/post");
    List <NameValuePair> nvps = new ArrayList <NameValuePair>();
    nvps.add(new BasicNameValuePair("username", "vip"));
    nvps.add(new BasicNameValuePair("password", "secret"));
    httpPost.setEntity(new UrlEncodedFormEntity(nvps));
    CloseableHttpResponse response2 = httpclient.execute(httpPost);
            
    try {
        System.out.println(response2.getStatusLine());
        HttpEntity entity2 = response2.getEntity();
        // do something useful with the response body
        // and ensure it is fully consumed
        EntityUtils.consume(entity2);
    } finally {
        response2.close();
    }
    } finally {
    httpclient.close();
    }*/
    try {
        HttpPost request = new HttpPost("http://www.sentiment140.com/api/bulkClassifyJson");
        StringEntity params = new StringEntity(jsonObject.toString());
        request.addHeader("content-type", "application/json");
        request.setEntity(params);
        HttpResponse response = httpclient.execute(request);
        System.out.println(response.toString());
        String result = EntityUtils.toString(response.getEntity());
        System.out.println(result);
        try {
            File file = new File("/Users/vikasmohandoss/Documents/Cloud/sentiment.txt");
            // if file doesnt exists, then create it
            if (!file.exists()) {
                file.createNewFile();
            }
            FileWriter fw = new FileWriter(file.getAbsoluteFile());
            BufferedWriter bw = new BufferedWriter(fw);
            bw.write(result);
            bw.close();
            System.out.println("Done");
        } catch (IOException e) {
            e.printStackTrace();
        }
        // handle response here...
    } catch (Exception ex) {
        // handle exception here
    } finally {
        httpclient.close();
    }
}

From source file:eu.mrbussy.pdfsplitter.Application.java

/**
 * Start the main program./* w  ww  . j av  a  2  s .c o  m*/
 * 
 * @param args
 *            - Arguments passed on to the program
 */
public static void main(String[] args) {

    // Read configurations
    try {
        String configDirname = FilenameUtils.concat(System.getProperty("user.home"),
                String.format(".%1$s%2$s", NAME, IOUtils.DIR_SEPARATOR));
        String filename = FilenameUtils.concat(configDirname, CONFIGURATION_FILE);

        // Check to see if the directory exists and the file can be created/opened
        File configDir = new File(configDirname);
        if (!configDir.exists())
            configDir.mkdir();

        // Check to see if the file exists. If not create it
        File file = new File(filename);
        if (!file.exists()) {
            file.createNewFile();
        }
        Configuration = new PropertiesConfiguration(file);
        // Automatically store the settings that change
        Configuration.setAutoSave(true);

    } catch (ConfigurationException | IOException ex) {
        // Unable to read the file. Probably because it does not exist --> create it.
        ex.printStackTrace();
    }

    // Set locale to a configured language
    Locale.setDefault(
            new Locale(Configuration.getString("language", "nl"), Configuration.getString("country", "NL")));

    // Start by parsing the command line
    ParseCommandline(args);

    // Display the help if required and leave the app
    if (arguments.hasOption("h")) {
        showHelp();
    }

    // Display the app version and leave the app.
    if (arguments.hasOption("v")) {
        showVersion();
    }

    // Not command line so start the app GUI
    if (!arguments.hasOption("c")) {
        try {
            // Change the look and feel
            UIManager.setLookAndFeel(
                    Configuration.getString("LookAndFeel", "com.sun.java.swing.plaf.gtk.GTKLookAndFeel"));
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    (new MainWindow()).setVisible(true);
                }
            });
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException
                | UnsupportedLookAndFeelException e) {
            // Something terrible happened so show the  help
            showHelp();
        }

    }

}

From source file:org.soasecurity.wso2.mutual.auth.oauth2.client.MutualSSLOAuthClient.java

public static void main(String[] args) throws Exception {

    File file = new File((new File(".")).getCanonicalPath() + File.separator + "src" + File.separator + "main"
            + File.separator + "resources" + File.separator + "keystore" + File.separator + keyStoreName);

    if (!file.exists()) {
        throw new Exception("Key Store file can not be found in " + file.getCanonicalPath());
    }//w w  w  .  j a v  a2 s  . c  o  m

    //Set trust store, you need to import server's certificate of CA certificate chain in to this
    //key store
    System.setProperty("javax.net.ssl.trustStore", file.getCanonicalPath());
    System.setProperty("javax.net.ssl.trustStorePassword", keyStorePassword);

    //Set key store, this must contain the user private key
    //here we have use both trust store and key store as the same key store
    //But you can use a separate key store for key store an trust store.
    System.setProperty("javax.net.ssl.keyStore", file.getCanonicalPath());
    System.setProperty("javax.net.ssl.keyStorePassword", keyStorePassword);

    HttpClient client = new HttpClient();

    HttpMethod method = new PostMethod(endPoint);

    // Base64 encoded client id & secret
    method.setRequestHeader("Authorization",
            "Basic T09pN2dpUjUwdDZtUmU1ZkpmWUhVelhVa1QwYTpOOUI2dDZxQ0E2RFp2eTJPQkFIWDhjVlI1eUlh");
    method.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

    NameValuePair pair1 = new NameValuePair();
    pair1.setName("grant_type");
    pair1.setValue("x509");

    NameValuePair pair2 = new NameValuePair();
    pair2.setName("username");
    pair2.setValue("asela");

    NameValuePair pair3 = new NameValuePair();
    pair3.setName("password");
    pair3.setValue("asela");

    method.setQueryString(new NameValuePair[] { pair1, pair2, pair3 });

    int statusCode = client.executeMethod(method);

    if (statusCode != HttpStatus.SC_OK) {

        System.out.println("Failed: " + method.getStatusLine());

    } else {

        byte[] responseBody = method.getResponseBody();

        System.out.println(new String(responseBody));
    }
}

From source file:com.p2p.peercds.cli.TorrentMain.java

/**
 * Torrent reader and creator.//from ww w  . j  a v a2 s  . c  om
 *
 * <p>
 * You can use the {@code main()} function of this class to read or create
 * torrent files. See usage for details.
 * </p>
 *
 */
public static void main(String[] args) {
    BasicConfigurator.configure(new ConsoleAppender(new PatternLayout("%-5p: %m%n")));

    CmdLineParser parser = new CmdLineParser();
    CmdLineParser.Option help = parser.addBooleanOption('h', "help");
    CmdLineParser.Option filename = parser.addStringOption('t', "torrent");
    CmdLineParser.Option create = parser.addBooleanOption('c', "create");
    CmdLineParser.Option announce = parser.addStringOption('a', "announce");

    try {
        parser.parse(args);
    } catch (CmdLineParser.OptionException oe) {
        System.err.println(oe.getMessage());
        usage(System.err);
        System.exit(1);
    }

    // Display help and exit if requested
    if (Boolean.TRUE.equals((Boolean) parser.getOptionValue(help))) {
        usage(System.out);
        System.exit(0);
    }

    String filenameValue = (String) parser.getOptionValue(filename);
    if (filenameValue == null) {
        usage(System.err, "Torrent file must be provided!");
        System.exit(1);
    }

    Boolean createFlag = (Boolean) parser.getOptionValue(create);

    //For repeated announce urls
    @SuppressWarnings("unchecked")
    Vector<String> announceURLs = (Vector<String>) parser.getOptionValues(announce);

    String[] otherArgs = parser.getRemainingArgs();

    if (Boolean.TRUE.equals(createFlag) && (otherArgs.length != 1 || announceURLs.isEmpty())) {
        usage(System.err,
                "Announce URL and a file or directory must be " + "provided to create a torrent file!");
        System.exit(1);
    }

    OutputStream fos = null;
    try {
        if (Boolean.TRUE.equals(createFlag)) {
            if (filenameValue != null) {
                fos = new FileOutputStream(filenameValue);
            } else {
                fos = System.out;
            }

            //Process the announce URLs into URIs
            List<URI> announceURIs = new ArrayList<URI>();
            for (String url : announceURLs) {
                announceURIs.add(new URI(url));
            }

            //Create the announce-list as a list of lists of URIs
            //Assume all the URI's are first tier trackers
            List<List<URI>> announceList = new ArrayList<List<URI>>();
            announceList.add(announceURIs);

            File source = new File(otherArgs[0]);
            if (!source.exists() || !source.canRead()) {
                throw new IllegalArgumentException(
                        "Cannot access source file or directory " + source.getName());
            }

            String creator = String.format("%s (ttorrent)", System.getProperty("user.name"));

            Torrent torrent = null;
            if (source.isDirectory()) {
                File[] files = source.listFiles(Constants.hiddenFilesFilter);
                Arrays.sort(files);
                torrent = Torrent.create(source, Arrays.asList(files), announceList, creator);
            } else {
                torrent = Torrent.create(source, announceList, creator);

            }

            torrent.save(fos);
        } else {
            Torrent.load(new File(filenameValue), true);
        }
    } catch (Exception e) {
        logger.error("{}", e.getMessage(), e);
        System.exit(2);
    } finally {
        if (fos != System.out) {
            IOUtils.closeQuietly(fos);
        }
    }
}

From source file:net.sourceforge.msscodefactory.cfasterisk.v2_4.CFAsteriskSwingHttpCLI.CFAsteriskSwingHttpCLI.java

public static void main(String args[]) {
    final String S_ProcName = "CFAsteriskSwingHttpCLI.main() ";
    initConsoleLog();/*w ww .ja  v  a  2 s.  c o m*/
    boolean fastExit = false;

    String homeDirName = System.getProperty("HOME");
    if (homeDirName == null) {
        homeDirName = System.getProperty("user.home");
        if (homeDirName == null) {
            log.message(S_ProcName + "ERROR: Home directory not set");
            return;
        }
    }
    File homeDir = new File(homeDirName);
    if (!homeDir.exists()) {
        log.message(S_ProcName + "ERROR: Home directory \"" + homeDirName + "\" does not exist");
        return;
    }
    if (!homeDir.isDirectory()) {
        log.message(S_ProcName + "ERROR: Home directory \"" + homeDirName + "\" is not a directory");
        return;
    }

    CFAsteriskClientConfigurationFile cFAsteriskClientConfig = new CFAsteriskClientConfigurationFile();
    String cFAsteriskClientConfigFileName = homeDir.getPath() + File.separator + ".cfasteriskclientrc";
    cFAsteriskClientConfig.setFileName(cFAsteriskClientConfigFileName);
    File cFAsteriskClientConfigFile = new File(cFAsteriskClientConfigFileName);
    if (!cFAsteriskClientConfigFile.exists()) {
        String cFAsteriskKeyStoreFileName = homeDir.getPath() + File.separator + ".msscfjceks";
        cFAsteriskClientConfig.setKeyStore(cFAsteriskKeyStoreFileName);
        InetAddress localHost;
        try {
            localHost = InetAddress.getLocalHost();
        } catch (UnknownHostException e) {
            localHost = null;
        }
        if (localHost == null) {
            log.message(S_ProcName + "ERROR: LocalHost is null");
            return;
        }
        String hostName = localHost.getHostName();
        if ((hostName == null) || (hostName.length() <= 0)) {
            log.message("ERROR: LocalHost.HostName is null or empty");
            return;
        }
        String userName = System.getProperty("user.name");
        if ((userName == null) || (userName.length() <= 0)) {
            log.message("ERROR: user.name is null or empty");
            return;
        }
        String deviceName = hostName.replaceAll("[^\\w]", "_").toLowerCase() + "-"
                + userName.replaceAll("[^\\w]", "_").toLowerCase();
        cFAsteriskClientConfig.setDeviceName(deviceName);
        cFAsteriskClientConfig.save();
        log.message(S_ProcName + "INFO: Created CFAsterisk client configuration file "
                + cFAsteriskClientConfigFileName);
        fastExit = true;
    }
    if (!cFAsteriskClientConfigFile.isFile()) {
        log.message(S_ProcName + "ERROR: Proposed client configuration file " + cFAsteriskClientConfigFileName
                + " is not a file.");
        fastExit = true;
    }
    if (!cFAsteriskClientConfigFile.canRead()) {
        log.message(S_ProcName + "ERROR: Permission denied attempting to read client configuration file "
                + cFAsteriskClientConfigFileName);
        fastExit = true;
    }
    cFAsteriskClientConfig.load();

    if (fastExit) {
        return;
    }

    // Configure logging
    Properties sysProps = System.getProperties();
    sysProps.setProperty("log4j.rootCategory", "WARN");
    sysProps.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.Log4JLogger");

    Logger httpLogger = Logger.getLogger("org.apache.http");
    httpLogger.setLevel(Level.WARN);

    // The Invoker and it's implementation
    CFAsteriskXMsgClientHttpSchema invoker = new CFAsteriskXMsgClientHttpSchema();

    // And now for the client side cache implementation that invokes it
    ICFAsteriskSchemaObj clientSchemaObj = new CFAsteriskSchemaObj() {
        public void logout() {
            CFAsteriskXMsgClientHttpSchema invoker = (CFAsteriskXMsgClientHttpSchema) getBackingStore();
            try {
                invoker.logout(getAuthorization());
            } catch (RuntimeException e) {
            }
            setAuthorization(null);
        }
    };
    clientSchemaObj.setBackingStore(invoker);
    // And stitch the response handler to reference our client instance
    invoker.setResponseHandlerSchemaObj(clientSchemaObj);
    // And now we can stitch together the CLI to the SAX loader code
    CFAsteriskSwingHttpCLI cli = new CFAsteriskSwingHttpCLI();
    cli.setXMsgClientHttpSchema(invoker);
    cli.setSchema(clientSchemaObj);
    ICFAsteriskSwingSchema swing = cli.getSwingSchema();
    swing.setClientConfigurationFile(cFAsteriskClientConfig);
    swing.setSchema(clientSchemaObj);
    swing.setClusterName("system");
    swing.setTenantName("system");
    swing.setSecUserName("system");
    JFrame jframe = cli.getDesktop();
    jframe.setVisible(true);
    jframe.toFront();
}

From source file:net.minecraftforge.fml.common.asm.transformers.MarkerTransformer.java

public static void main(String[] args) {
    if (args.length < 2) {
        System.out.println("Usage: MarkerTransformer <JarPath> <MapFile> [MapFile2]... ");
        return;/*from  w w  w .j ava 2  s .  c o m*/
    }

    boolean hasTransformer = false;
    MarkerTransformer[] trans = new MarkerTransformer[args.length - 1];
    for (int x = 1; x < args.length; x++) {
        try {
            trans[x - 1] = new MarkerTransformer(args[x]);
            hasTransformer = true;
        } catch (IOException e) {
            System.out.println("Could not read Transformer Map: " + args[x]);
            e.printStackTrace();
        }
    }

    if (!hasTransformer) {
        System.out.println("Could not find a valid transformer to perform");
        return;
    }

    File orig = new File(args[0]);
    File temp = new File(args[0] + ".ATBack");
    if (!orig.exists() && !temp.exists()) {
        System.out.println("Could not find target jar: " + orig);
        return;
    }
    /*
            if (temp.exists())
            {
    if (orig.exists() && !orig.renameTo(new File(args[0] + (new SimpleDateFormat(".yyyy.MM.dd.HHmmss")).format(new Date()))))
    {
        System.out.println("Could not backup existing file: " + orig);
        return;
    }
    if (!temp.renameTo(orig))
    {
        System.out.println("Could not restore backup from previous run: " + temp);
        return;
    }
            }
    */
    if (!orig.renameTo(temp)) {
        System.out.println("Could not rename file: " + orig + " -> " + temp);
        return;
    }

    try {
        processJar(temp, orig, trans);
    } catch (IOException e) {
        e.printStackTrace();
    }

    if (!temp.delete()) {
        System.out.println("Could not delete temp file: " + temp);
    }
}

From source file:mil.tatrc.physiology.utilities.csv.plots.CSVPlotTool.java

public static void main(String[] args) {
    if (args.length < 1) {
        Log.fatal("Expected inputs : [results file path]");
        return;//from  w w w .ja v a2s  . c  o m
    }
    File f = new File(args[0]);
    if (!f.exists()) {
        Log.fatal("Input file cannot be found");
        return;
    }
    String reportDir = "./graph_results/" + f.getName();
    reportDir = reportDir.substring(0, reportDir.lastIndexOf(".")) + "/";
    CSVPlotTool t = new CSVPlotTool();
    t.graphResults(args[0], reportDir);
}

From source file:com.sangupta.snowpack.SnowpackRecover.java

public static void main(String[] args) {
    if (args.length != 1) {
        System.out.println(//from w w  w. j  a  va  2  s.c  om
                "Usage: java -classpath snowpack.jar com.sangupta.snowpack.SnowpackRecover <base-folder>");
        return;
    }

    File base = new File(args[0]);
    if (!base.exists()) {
        System.out.println("Base folder does not exists.");
        return;
    }

    if (!base.isDirectory()) {
        System.out.println("Base folder does not represent a valid directory on disk.");
        return;
    }

    long start = System.currentTimeMillis();
    recover(base);
    long end = System.currentTimeMillis();

    System.out.println("Recovery process complete in " + (end - start) + "ms.");
}

From source file:gr.csri.poeticon.praxicon.CreateNeo4JDB.java

public static void main(final String[] args) {
    if (args.length > 0) {
        if (args[0] != null && args[0].length() > 0) {
            File f = new File(args[0]);
            if (f.exists() && f.isDirectory()) {
                DB_PATH = args[0];//from w  ww.  j  av  a 2s .  c  o m
            }
        }
    }
    CreateNeo4JDB myNeoInstance = new CreateNeo4JDB();
    myNeoInstance.dropDb();
    myNeoInstance.createGraph();
    myNeoInstance.shutDown();
    System.exit(0);
}

From source file:com.linkedin.pinotdruidbenchmark.DruidResponseTime.java

public static void main(String[] args) throws Exception {
    if (args.length != 4 && args.length != 5) {
        System.err.println(/*from   www  .  j  a va  2s .  co m*/
                "4 or 5 arguments required: QUERY_DIR, RESOURCE_URL, WARM_UP_ROUNDS, TEST_ROUNDS, RESULT_DIR (optional).");
        return;
    }

    File queryDir = new File(args[0]);
    String resourceUrl = args[1];
    int warmUpRounds = Integer.parseInt(args[2]);
    int testRounds = Integer.parseInt(args[3]);
    File resultDir;
    if (args.length == 4) {
        resultDir = null;
    } else {
        resultDir = new File(args[4]);
        if (!resultDir.exists()) {
            if (!resultDir.mkdirs()) {
                throw new RuntimeException("Failed to create result directory: " + resultDir);
            }
        }
    }

    File[] queryFiles = queryDir.listFiles();
    assert queryFiles != null;
    Arrays.sort(queryFiles);

    try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
        HttpPost httpPost = new HttpPost(resourceUrl);
        httpPost.addHeader("content-type", "application/json");

        for (File queryFile : queryFiles) {
            StringBuilder stringBuilder = new StringBuilder();
            try (BufferedReader bufferedReader = new BufferedReader(new FileReader(queryFile))) {
                int length;
                while ((length = bufferedReader.read(CHAR_BUFFER)) > 0) {
                    stringBuilder.append(new String(CHAR_BUFFER, 0, length));
                }
            }
            String query = stringBuilder.toString();
            httpPost.setEntity(new StringEntity(query));

            System.out.println(
                    "--------------------------------------------------------------------------------");
            System.out.println("Running query: " + query);
            System.out.println(
                    "--------------------------------------------------------------------------------");

            // Warm-up Rounds
            System.out.println("Run " + warmUpRounds + " times to warm up...");
            for (int i = 0; i < warmUpRounds; i++) {
                CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
                httpResponse.close();
                System.out.print('*');
            }
            System.out.println();

            // Test Rounds
            System.out.println("Run " + testRounds + " times to get response time statistics...");
            long[] responseTimes = new long[testRounds];
            long totalResponseTime = 0L;
            for (int i = 0; i < testRounds; i++) {
                long startTime = System.currentTimeMillis();
                CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
                httpResponse.close();
                long responseTime = System.currentTimeMillis() - startTime;
                responseTimes[i] = responseTime;
                totalResponseTime += responseTime;
                System.out.print(responseTime + "ms ");
            }
            System.out.println();

            // Store result.
            if (resultDir != null) {
                File resultFile = new File(resultDir, queryFile.getName() + ".result");
                CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
                try (BufferedInputStream bufferedInputStream = new BufferedInputStream(
                        httpResponse.getEntity().getContent());
                        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(resultFile))) {
                    int length;
                    while ((length = bufferedInputStream.read(BYTE_BUFFER)) > 0) {
                        bufferedWriter.write(new String(BYTE_BUFFER, 0, length));
                    }
                }
                httpResponse.close();
            }

            // Process response times.
            double averageResponseTime = (double) totalResponseTime / testRounds;
            double temp = 0;
            for (long responseTime : responseTimes) {
                temp += (responseTime - averageResponseTime) * (responseTime - averageResponseTime);
            }
            double standardDeviation = Math.sqrt(temp / testRounds);
            System.out.println("Average response time: " + averageResponseTime + "ms");
            System.out.println("Standard deviation: " + standardDeviation);
        }
    }
}