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.khubla.jvmbasic.jvmbasicc.JVMBasic.java

/**
 * start here//from   www .  java 2  s. c  o  m
 * <p>
 * -file src\test\resources\bas\easy\print.bas -verbose true
 * </p>
 */
public static void main(String[] args) {
    try {
        System.out.println("khubla.com jvmBASIC Compiler");
        /*
         * options
         */
        final Options options = new Options();
        Option oo = Option.builder().argName(OUTPUT_OPTION).longOpt(OUTPUT_OPTION).type(String.class).hasArg()
                .required(false).desc("target directory to output to").build();
        options.addOption(oo);
        oo = Option.builder().argName(FILE_OPTION).longOpt(FILE_OPTION).type(String.class).hasArg()
                .required(true).desc("file to compile").build();
        options.addOption(oo);
        oo = Option.builder().argName(VERBOSE_OPTION).longOpt(VERBOSE_OPTION).type(String.class).hasArg()
                .required(false).desc("verbose output").build();
        options.addOption(oo);
        /*
         * parse
         */
        final CommandLineParser parser = new DefaultParser();
        CommandLine cmd = null;
        try {
            cmd = parser.parse(options, args);
        } catch (final Exception e) {
            e.printStackTrace();
            final HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("posix", options);
            System.exit(0);
        }
        /*
         * verbose output?
         */
        final Boolean verbose = Boolean.parseBoolean(cmd.getOptionValue(VERBOSE_OPTION));
        /*
         * get the file
         */
        final String filename = cmd.getOptionValue(FILE_OPTION);
        final String outputDirectory = cmd.getOptionValue(OUTPUT_OPTION);
        if (null != filename) {
            /*
             * filename
             */
            final String basFileName = System.getProperty("user.dir") + "/" + filename;
            final File fl = new File(basFileName);
            if (true == fl.exists()) {
                /*
                 * show the filename
                 */
                System.out.println("Compiling: " + fl.getCanonicalFile());
                /*
                 * compiler
                 */
                final JVMBasicCompiler jvmBasicCompiler = new JVMBasicCompiler();
                /*
                 * compile
                 */
                jvmBasicCompiler.compileToClassfile(basFileName, null, outputDirectory, verbose, true, true);
            } else {
                throw new Exception("Unable to find: '" + basFileName + "'");
            }
        } else {
            throw new Exception("File was not supplied");
        }
    } catch (final Exception e) {
        e.printStackTrace();
    }
}

From source file:com.moss.error_reporting.server.ErrorReportServer.java

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

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

    if (log4jConfigFile.exists()) {
        DOMConfigurator.configureAndWatch(log4jConfigFile.getAbsolutePath(), 1000);
        System.out.println("Configuring with log file " + log4jConfigFile.getAbsolutePath());
    } else {//from  w  w  w. j a va 2s  . c  o  m
        BasicConfigurator.configure();
        Logger.getRootLogger().setLevel(Level.INFO);
    }

    ServerConfiguration config;

    JAXBContext context = JAXBContext.newInstance(ServerConfiguration.class);
    JAXBHelper helper = new JAXBHelper(context);

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

    if (!configFile.exists()) {

        config = new ServerConfiguration();
        helper.writeToFile(helper.writeToXmlString(config), configFile);
        System.out.println("Created default config file at " + configFile.getAbsolutePath());

    } else {
        System.out.println("Reading config file at " + configFile.getAbsolutePath());
        config = helper.readFromFile(configFile);
    }
    new ErrorReportServer(config);
}

From source file:com.rabbitmq.examples.FileConsumer.java

public static void main(String[] args) {
    Options options = new Options();
    options.addOption(new Option("h", "uri", true, "AMQP URI"));
    options.addOption(new Option("q", "queue", true, "queue name"));
    options.addOption(new Option("t", "type", true, "exchange type"));
    options.addOption(new Option("e", "exchange", true, "exchange name"));
    options.addOption(new Option("k", "routing-key", true, "routing key"));
    options.addOption(new Option("d", "directory", true, "output directory"));

    CommandLineParser parser = new GnuParser();

    try {//  w  w w  .  j  a v  a 2 s  . c o  m
        CommandLine cmd = parser.parse(options, args);

        String uri = strArg(cmd, 'h', "amqp://localhost");
        String requestedQueueName = strArg(cmd, 'q', "");
        String exchangeType = strArg(cmd, 't', "direct");
        String exchange = strArg(cmd, 'e', null);
        String routingKey = strArg(cmd, 'k', null);
        String outputDirName = strArg(cmd, 'd', ".");

        File outputDir = new File(outputDirName);
        if (!outputDir.exists() || !outputDir.isDirectory()) {
            System.err.println("Output directory must exist, and must be a directory.");
            System.exit(2);
        }

        ConnectionFactory connFactory = new ConnectionFactory();
        connFactory.setUri(uri);
        Connection conn = connFactory.newConnection();

        final Channel ch = conn.createChannel();

        String queueName = (requestedQueueName.equals("") ? ch.queueDeclare()
                : ch.queueDeclare(requestedQueueName, false, false, false, null)).getQueue();

        if (exchange != null || routingKey != null) {
            if (exchange == null) {
                System.err.println("Please supply exchange name to bind to (-e)");
                System.exit(2);
            }
            if (routingKey == null) {
                System.err.println("Please supply routing key pattern to bind to (-k)");
                System.exit(2);
            }
            ch.exchangeDeclare(exchange, exchangeType);
            ch.queueBind(queueName, exchange, routingKey);
        }

        QueueingConsumer consumer = new QueueingConsumer(ch);
        ch.basicConsume(queueName, consumer);
        while (true) {
            QueueingConsumer.Delivery delivery = consumer.nextDelivery();
            Map<String, Object> headers = delivery.getProperties().getHeaders();
            byte[] body = delivery.getBody();
            Object headerFilenameO = headers.get("filename");
            String headerFilename = (headerFilenameO == null) ? UUID.randomUUID().toString()
                    : headerFilenameO.toString();
            File givenName = new File(headerFilename);
            if (givenName.getName().equals("")) {
                System.out.println("Skipping file with empty name: " + givenName);
            } else {
                File f = new File(outputDir, givenName.getName());
                System.out.print("Writing " + f + " ...");
                FileOutputStream o = new FileOutputStream(f);
                o.write(body);
                o.close();
                System.out.println(" done.");
            }
            ch.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
        }
    } catch (Exception ex) {
        System.err.println("Main thread caught exception: " + ex);
        ex.printStackTrace();
        System.exit(1);
    }
}

From source file:edu.harvard.hul.ois.fits.clients.FormFileUploaderClientApplication.java

/**
 * Run the program.// w  w w.j a v  a  2  s.c o  m
 *
 * @param args First argument is path to the file to analyze; second (optional) is path to server for overriding default value.
 */
public static void main(String[] args) {
    // takes file path from first program's argument
    if (args.length < 1) {
        logger.error("****** Path to input file must be first argument to program! *******");
        logger.error("===== Exiting Program =====");
        System.exit(1);
    }

    String filePath = args[0];
    File uploadFile = new File(filePath);
    if (!uploadFile.exists()) {
        logger.error("****** File does not exist at expected locations! *******");
        logger.error("===== Exiting Program =====");
        System.exit(1);
    }

    if (args.length > 1) {
        serverUrl = args[1];
    }

    logger.info("File to upload: " + filePath);

    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {
        HttpPost httppost = new HttpPost(serverUrl + "false");
        FileBody bin = new FileBody(uploadFile);
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.addPart(FITS_FORM_FIELD_DATAFILE, bin);
        HttpEntity reqEntity = builder.build();
        httppost.setEntity(reqEntity);

        logger.info("executing request " + httppost.getRequestLine());
        CloseableHttpResponse response = httpclient.execute(httppost);
        try {
            logger.info("HTTP Response Status Line: " + response.getStatusLine());
            // Expecting a 200 Status Code
            if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                String reason = response.getStatusLine().getReasonPhrase();
                logger.warn("Unexpected HTTP response status code:[" + response.getStatusLine().getStatusCode()
                        + "] -- Reason (if available): " + reason);
            } else {
                HttpEntity resEntity = response.getEntity();
                InputStream is = resEntity.getContent();
                BufferedReader in = new BufferedReader(new InputStreamReader(is));

                String output;
                StringBuilder sb = new StringBuilder();
                while ((output = in.readLine()) != null) {
                    sb.append(output);
                    sb.append(System.getProperty("line.separator"));
                }
                logger.info(sb.toString());
                in.close();
                EntityUtils.consume(resEntity);
            }
        } finally {
            response.close();
        }
    } catch (Exception e) {
        logger.error("Caught exception: " + e.getMessage(), e);
    } finally {
        try {
            httpclient.close();
        } catch (IOException e) {
            logger.warn("Exception closing HTTP client: " + e.getMessage(), e);
        }
        logger.info("DONE");
    }
}

From source file:com.vitco.Main.java

public static void main(String[] args) throws Exception {
    // display version number on splash screen
    final SplashScreen splash = SplashScreen.getSplashScreen();
    if (splash != null) {
        Graphics2D g = splash.createGraphics();
        if (g != null) {
            g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
                    RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_HRGB);
            Font font = Font
                    .createFont(Font.TRUETYPE_FONT,
                            new SaveResourceLoader("resource/font/arcade.ttf").asInputStream())
                    .deriveFont(Font.PLAIN, 42f);
            g.setFont(font);//from  w  ww. j a  v  a  2  s.com
            //g.setFont(g.getFont().deriveFont(9f));
            g.setColor(VitcoSettings.SPLASH_SCREEN_OVERLAY_TEXT_COLOR);
            int width = g.getFontMetrics().stringWidth(VitcoSettings.VERSION_ID);
            g.drawString(VitcoSettings.VERSION_ID, 400 - 20 - width, 110);
            splash.update();
            g.dispose();
        }
    }

    // the JIDE license
    SaveResourceLoader saveResourceLoader = new SaveResourceLoader("resource/jidelicense.txt");
    if (!saveResourceLoader.error) {
        String[] jidelicense = saveResourceLoader.asLines();
        if (jidelicense.length == 3) {
            com.jidesoft.utils.Lm.verifyLicense(jidelicense[0], jidelicense[1], jidelicense[2]);
        }
    }

    // check if we are in debug mode
    if ((args.length > 0) && args[0].equals("debug")) {
        ErrorHandler.setDebugMode();
        debug = true;
    }

    // build the application
    final ConfigurableApplicationContext context = new ClassPathXmlApplicationContext(
            "com/vitco/glue/config.xml");

    // for debugging
    if (debug) {
        ((ActionManager) context.getBean("ActionManager")).performValidityCheck();
        ((ComplexActionManager) context.getBean("ComplexActionManager")).performValidityCheck();
    }

    // open vsd file when program is started with "open with"
    MainMenuLogic mainMenuLogic = ((MainMenuLogic) context.getBean("MainMenuLogic"));
    for (String arg : args) {
        if (arg.endsWith(".vsd")) {
            File file = new File(arg);
            if (file.exists() && !file.isDirectory()) {
                mainMenuLogic.openFile(file);
                break;
            }
        }
    }

    // perform shortcut check
    ((ShortcutManager) context.getBean("ShortcutManager")).doSanityCheck(debug);
    //        // test console
    //        final Console console = ((Console) context.getBean("Console"));
    //        new Thread() {
    //            public void run() {
    //                while (true) {
    //                    console.addLine("text");
    //                    try {
    //                        sleep(2000);
    //                    } catch (InterruptedException e) {
    //                       //e.printStackTrace();
    //                    }
    //                }
    //            }
    //        }.start();

    // add a shutdown hook
    Runtime.getRuntime().addShutdownHook(new Thread() {
        public void run() {
            // make reference so Preferences object doesn't get destroyed
            Preferences pref = ((Preferences) context.getBean("Preferences"));
            // trigger @PreDestroy
            context.close();
            // store the preferences (this needs to be done here, b/c
            // some PreDestroys are used to store preferences!)
            pref.save();
        }
    });
}

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

public static void main(String[] args) throws IOException {
    String inputDir = args[0];//  w ww .  j av a  2  s  .com

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

    computeRawLengthStatistics(inputDir);
}

From source file:examples.StatePersistence.java

public static void main(String[] args) throws Exception {
    // Connect to localhost and use the travel-sample bucket
    final Client client = Client.configure().hostnames("localhost").bucket(BUCKET).build();

    // Don't do anything with control events in this example
    client.controlEventHandler(new ControlEventHandler() {
        @Override/*from   ww w.  j  a  v a 2  s  .  c o  m*/
        public void onEvent(ChannelFlowController flowController, ByteBuf event) {
            if (DcpSnapshotMarkerRequest.is(event)) {
                flowController.ack(event);
            }
            event.release();
        }
    });

    // Print out Mutations and Deletions
    client.dataEventHandler(new DataEventHandler() {
        @Override
        public void onEvent(ChannelFlowController flowController, ByteBuf event) {
            if (DcpMutationMessage.is(event)) {
                System.out.println("Mutation: " + DcpMutationMessage.toString(event));
                // You can print the content via DcpMutationMessage.content(event).toString(CharsetUtil.UTF_8);
            } else if (DcpDeletionMessage.is(event)) {
                System.out.println("Deletion: " + DcpDeletionMessage.toString(event));
            }
            event.release();
        }
    });

    // Connect the sockets
    client.connect().await();

    // Try to load the persisted state from file if it exists
    File file = new File(FILENAME);
    byte[] persisted = null;
    if (file.exists()) {
        FileInputStream fis = new FileInputStream(FILENAME);
        persisted = IOUtils.toByteArray(fis);
        fis.close();
    }

    // if the persisted file exists recover, if not start from beginning
    client.recoverOrInitializeState(StateFormat.JSON, persisted, StreamFrom.BEGINNING, StreamTo.INFINITY)
            .await();

    // Start streaming on all partitions
    client.startStreaming().await();

    // Persist the State ever 10 seconds
    while (true) {
        Thread.sleep(TimeUnit.SECONDS.toMillis(10));

        // export the state as a JSON byte array
        byte[] state = client.sessionState().export(StateFormat.JSON);

        // Write it to a file
        FileOutputStream output = new FileOutputStream(new File(FILENAME));
        IOUtils.write(state, output);
        output.close();

        System.out.println(System.currentTimeMillis() + " - Persisted State!");
    }
}

From source file:android.example.hlsmerge.crypto.Main.java

public static void main(String[] args) {
    CommandLine commandLine = parseCommandLine(args);
    String[] commandLineArgs = commandLine.getArgs();

    try {//from   w w w .ja v a2 s  .c o m
        String playlistUrl = commandLineArgs[0];
        String outFile = null;
        String key = null;

        if (commandLine.hasOption(OPT_OUT_FILE)) {
            outFile = commandLine.getOptionValue(OPT_OUT_FILE);

            File file = new File(outFile);

            if (file.exists()) {
                if (!commandLine.hasOption(OPT_OVERWRITE)) {
                    System.out.printf("File '%s' already exists. Overwrite? [y/N] ", outFile);

                    int ch = System.in.read();

                    if (!(ch == 'y' || ch == 'Y')) {
                        System.exit(0);
                    }
                }

                file.delete();
            }
        }

        if (commandLine.hasOption(OPT_KEY))
            key = commandLine.getOptionValue(OPT_KEY);

        PlaylistDownloader downloader = new PlaylistDownloader(playlistUrl, null);

        if (commandLine.hasOption(OPT_SILENT)) {
            System.setOut(new PrintStream(new OutputStream() {
                public void close() {
                }

                public void flush() {
                }

                public void write(byte[] b) {
                }

                public void write(byte[] b, int off, int len) {
                }

                public void write(int b) {
                }
            }));
        }

        downloader.download(outFile, key);
    } catch (Exception e) {
        e.printStackTrace();
        System.exit(1);
    }
}

From source file:net.chrislongo.hls.Main.java

public static void main(String[] args) {
    CommandLine commandLine = parseCommandLine(args);
    String[] commandLineArgs = commandLine.getArgs();

    try {/*from w  ww .  ja v  a2s . c  om*/
        String playlistUrl = commandLineArgs[0];
        String outFile = null;
        String key = null;

        if (commandLine.hasOption(OPT_OUT_FILE)) {
            outFile = commandLine.getOptionValue(OPT_OUT_FILE);

            File file = new File(outFile);

            if (file.exists()) {
                if (!commandLine.hasOption(OPT_OVERWRITE)) {
                    System.out.printf("File '%s' already exists. Overwrite? [y/N] ", outFile);

                    int ch = System.in.read();

                    if (!(ch == 'y' || ch == 'Y')) {
                        System.exit(0);
                    }
                }

                file.delete();
            }
        }

        if (commandLine.hasOption(OPT_KEY))
            key = commandLine.getOptionValue(OPT_KEY);

        PlaylistDownloader downloader = new PlaylistDownloader(playlistUrl);

        if (commandLine.hasOption(OPT_SILENT)) {
            System.setOut(new PrintStream(new OutputStream() {
                public void close() {
                }

                public void flush() {
                }

                public void write(byte[] b) {
                }

                public void write(byte[] b, int off, int len) {
                }

                public void write(int b) {
                }
            }));
        }

        downloader.download(outFile, key);
    } catch (Exception e) {
        e.printStackTrace();
        System.exit(1);
    }
}

From source file:de.jackwhite20.japs.server.Main.java

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

    Config config = null;/*w w w  .  ja  v a2  s  .c o m*/

    if (args.length > 0) {
        Options options = new Options();
        options.addOption("h", true, "Address to bind to");
        options.addOption("p", true, "Port to bind to");
        options.addOption("b", true, "The backlog");
        options.addOption("t", true, "Worker thread count");
        options.addOption("d", false, "If debug is enabled or not");
        options.addOption("c", true, "Add server as a cluster");
        options.addOption("ci", true, "Sets the cache check interval");
        options.addOption("si", true, "Sets the snapshot interval");

        CommandLineParser commandLineParser = new BasicParser();
        CommandLine commandLine = commandLineParser.parse(options, args);

        if (commandLine.hasOption("h") && commandLine.hasOption("p") && commandLine.hasOption("b")
                && commandLine.hasOption("t")) {

            List<ClusterServer> clusterServers = new ArrayList<>();

            if (commandLine.hasOption("c")) {
                for (String c : commandLine.getOptionValues("c")) {
                    String[] splitted = c.split(":");
                    clusterServers.add(new ClusterServer(splitted[0], Integer.parseInt(splitted[1])));
                }
            }

            config = new Config(commandLine.getOptionValue("h"),
                    Integer.parseInt(commandLine.getOptionValue("p")),
                    Integer.parseInt(commandLine.getOptionValue("b")), commandLine.hasOption("d"),
                    Integer.parseInt(commandLine.getOptionValue("t")), clusterServers,
                    (commandLine.hasOption("ci")) ? Integer.parseInt(commandLine.getOptionValue("ci")) : 300,
                    (commandLine.hasOption("si")) ? Integer.parseInt(commandLine.getOptionValue("si")) : -1);
        } else {
            System.out.println(
                    "Usage: java -jar japs-server.jar -h <Host> -p <Port> -b <Backlog> -t <Threads> [-c IP:Port IP:Port] [-d]");
            System.out.println(
                    "Example (with debugging enabled): java -jar japs-server.jar -h localhost -p 1337 -b 100 -t 4 -d");
            System.out.println(
                    "Example (with debugging enabled and cluster setup): java -jar japs-server.jar -h localhost -p 1337 -b 100 -t 4 -c localhost:1338 -d");
            System.exit(-1);
        }
    } else {
        File configFile = new File("config.json");
        if (!configFile.exists()) {
            try {
                Files.copy(JaPS.class.getClassLoader().getResourceAsStream("config.json"), configFile.toPath(),
                        StandardCopyOption.REPLACE_EXISTING);
            } catch (IOException e) {
                System.err.println("Unable to load default config!");
                System.exit(-1);
            }
        }

        try {
            config = new Gson().fromJson(
                    Files.lines(configFile.toPath()).map(String::toString).collect(Collectors.joining(" ")),
                    Config.class);
        } catch (IOException e) {
            System.err.println("Unable to load 'config.json' in current directory!");
            System.exit(-1);
        }
    }

    if (config == null) {
        System.err.println("Failed to create a Config!");
        System.err.println("Please check the program parameters or the 'config.json' file!");
    } else {
        System.err.println("Using Config: " + config);

        JaPS jaPS = new JaPS(config);
        jaPS.init();
        jaPS.start();
        jaPS.stop();
    }
}