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.jff.searchapicluster.server.mina.Server.java

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

    org.apache.commons.configuration.Configuration config = new PropertiesConfiguration("settings.txt");

    int serverPort = config.getInt("listenPort");

    NioSocketAcceptor acceptor = new NioSocketAcceptor();

    acceptor.getFilterChain().addLast("com/jff/searchapicluster/core/mina/codec",
            new ProtocolCodecFilter(new ObjectSerializationCodecFactory()));

    acceptor.getFilterChain().addLast("logger", new LoggingFilter());

    acceptor.setHandler(new ServerSessionHandler());
    acceptor.bind(new InetSocketAddress(serverPort));

    System.out.println("Listening on port " + serverPort);
    System.out.println("Please enter filename");

    //  open up standard input
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

    while (true) {
        String filepath = br.readLine();

        filepath = "/Users/admin/repos/study_repos/kurs_sp/search_api_cluster/SearchApiClusterServer/task.json";
        File file = new File(filepath);
        Logger.d(LOG_TAG, file.getAbsolutePath());

        if (file.exists() && file.isFile()) {

            Gson gson = new Gson();

            SearchTask taskMessage = gson.fromJson(new FileReader(file), SearchTask.class);

            ServerManager serverManager = ServerManager.getInstance();

            Logger.d(LOG_TAG, taskMessage.toString());
            serverManager.startProcessTask(taskMessage);
        } else {/*from w  w w.j av  a  2s . c  o m*/
            Logger.d(LOG_TAG, filepath + "not found");
        }
    }
}

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

public static void main(String[] args) throws IOException {
    // input dir - list of xml query containers
    // step2a-retrieved-results
    File inputDir = new File(args[0]);

    // warc.bz file containing all required documents according to ClueWeb IDs
    // ltr-50queries-100docs-clueweb-export.warc.gz
    File warc = new File(args[1]);

    // output dir
    File outputDir = new File(args[2]);
    if (!outputDir.exists()) {
        outputDir.mkdirs();/*from  ww  w  .j  ava2  s  .  co m*/
    }

    // iterate over query containers
    for (File f : FileUtils.listFiles(inputDir, new String[] { "xml" }, false)) {
        QueryResultContainer queryResultContainer = QueryResultContainer
                .fromXML(FileUtils.readFileToString(f, "utf-8"));

        // iterate over warc for each query
        WARCFileReader reader = new WARCFileReader(new Configuration(), new Path(warc.getAbsolutePath()));
        try {
            while (true) {
                WARCRecord read = reader.read();
                String trecId = read.getHeader().getField("WARC-TREC-ID");

                // now iterate over retrieved results for the query and find matching IDs
                for (QueryResultContainer.SingleRankedResult rankedResults : queryResultContainer.rankedResults) {
                    if (rankedResults.clueWebID.equals(trecId)) {
                        // add the raw html content
                        String fullHTTPResponse = new String(read.getContent(), "utf-8");
                        // TODO fix coding?

                        String html = removeHTTPHeaders(fullHTTPResponse);

                        rankedResults.originalHtml = sanitizeXmlChars(html.trim());
                    }
                }
            }
        } catch (EOFException e) {
            // end of file
        }

        // check if all results have filled html
        for (QueryResultContainer.SingleRankedResult rankedResults : queryResultContainer.rankedResults) {
            if (rankedResults.originalHtml == null) {
                System.err.println("Missing original html for\t" + rankedResults.clueWebID
                        + ", setting relevance to false");
                rankedResults.relevant = Boolean.FALSE.toString();
            }
        }

        // and save the query to output dir
        File outputFile = new File(outputDir, queryResultContainer.qID + ".xml");
        FileUtils.writeStringToFile(outputFile, queryResultContainer.toXML(), "utf-8");
        System.out.println("Finished " + outputFile);
    }

}

From source file:hisqisnoten.HisqisNoten.java

public static void main(String[] args) {
    options = new Options();
    options.addOption("h", "help", false, "this help");
    options.addOption("u", "user", true, "username for hisqis");
    options.addOption("p", "pass", true, "password for hisqis");
    options.addOption("c", "console", false, "console mode instead of gui mode");

    CommandLineParser parser = new PosixParser();

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

        if (cmdline.hasOption("help")) {
            printHelp();
            System.exit(0);
        }

        if (cmdline.getArgList().size() != 0) {
            System.err.println("Please use the new commandline options.");
            System.out.println();

            printHelp();
            System.exit(1);
        }

        HisqisSettings settings = null;
        HisqisSettings.genConfigPath();

        for (File configpath : HisqisSettings.configpath) {
            if (configpath.exists() && configpath.canRead()) {
                settings = HisqisSettingsReader.loadDocument(configpath);

                if (settings != null) {
                    break;
                }
            }
        }

        if (settings == null) {
            settings = new HisqisSettings();
        }

        String user = cmdline.getOptionValue("user", null);
        String pass = cmdline.getOptionValue("pass", null);

        if (user != null) {
            settings.username = user;
        }
        if (pass != null) {
            settings.password = pass;
        }

        if (cmdline.hasOption("console")) {
            new HisqisConsole(settings);
        } else {
            new HisqisGUI(settings);
        }
    } catch (ParseException e) {
        printHelp();
    }
}

From source file:org.atomserver.utils.jetty.StandAloneAtomServer.java

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

    // the System Property "atomserver.home" defines the home directory for the standalone app
    String atomserverHome = System.getProperty("atomserver.home");
    if (StringUtils.isEmpty(atomserverHome)) {
        log.error("The variable \"atomserver.home\" must be defined");
        System.exit(-1);/*  ww w  . j a  v  a 2s .c  om*/
    }
    File atomserverHomeDir = new File(atomserverHome);
    if (!atomserverHomeDir.exists() && !atomserverHomeDir.isDirectory()) {
        log.error("The variable \"atomserver.home\" (" + atomserverHome
                + ") must point to a directory that exists");
    }

    // instantiate the Jetty Server
    Server server = new Server();

    // create a new connector on the declared port, and set it onto the server
    log.debug("atomserver.port = " + System.getProperty("atomserver.port"));
    Connector connector = new SelectChannelConnector();
    connector.setPort(Integer.getInteger("atomserver.port", DEFAULT_PORT));
    server.setConnectors(new Connector[] { connector });

    // create a ClassLoader that points at the conf directories
    log.debug("atomserver.conf.dir = " + System.getProperty("atomserver.conf.dir"));
    log.debug("atomserver.ops.conf.dir = " + System.getProperty("atomserver.ops.conf.dir"));
    ClassLoader classLoader = new ConfigurationAwareClassLoader(StandAloneAtomServer.class.getClassLoader());

    // load the version from the version.properties file
    Properties versionProps = new Properties();
    versionProps.load(classLoader.getResourceAsStream(DEFAULT_VERSIONS_FILE));
    String version = versionProps.getProperty("atomserver.version");

    // create a new webapp, rooted at webapps/atomserver-${version}, with the configured
    // context name
    String servletContextName = System.getProperty("atomserver.servlet.context");
    log.debug("atomserver.servlet.context = " + servletContextName);
    WebAppContext webapp = new WebAppContext(atomserverHome + "/webapps/atomserver-" + version,
            "/" + servletContextName);

    // set the webapp's ClassLoader to be the one that loaded THIS class.  the REASON that
    // this needs to be set is so that when we extract the web application context below we can
    // cast it to WebApplicationContext here
    webapp.setClassLoader(StandAloneAtomServer.class.getClassLoader());

    // set the Jetty server's webapp and start it
    server.setHandler(webapp);
    server.start();

    // if the seed system property was set, use the DBSeeder to populate the server
    String seedDB = System.getProperty("seed.database.with.pets");
    log.debug("seed.database.with.pets = " + seedDB);
    if (!StringUtils.isEmpty(seedDB)) {
        if (Boolean.valueOf(seedDB)) {
            Thread.sleep(2000);

            WebApplicationContext webappContext = WebApplicationContextUtils
                    .getWebApplicationContext(webapp.getServletContext());

            DBSeeder.getInstance(webappContext).seedPets();
        }
    }

    server.join();
}

From source file:me.rgcjonas.portableMinecraftLauncher.Main.java

/**
 * entry point/*from   w  w  w . j ava2  s.  co  m*/
 * @param args
 */
public static void main(String[] args) {
    File workDir = getWorkingDirectory();

    //ensure the working directory exists
    if (!workDir.exists()) {
        workDir.mkdir();
    }
    File launcherJar = new File(workDir, "launcher.jar");

    //download launcher if it doesn't exist
    if (!launcherJar.exists()) {
        try {
            URL launcherurl = new URL("https://s3.amazonaws.com/MinecraftDownload/launcher/minecraft.jar");
            FileUtils.copyURLToFile(launcherurl, launcherJar);
        } catch (IOException e) {
            // shouldn't happen
            e.printStackTrace();
        }
    }

    URL[] urls;
    try {
        urls = new URL[] { launcherJar.toURI().toURL() };

        //this class loader mustn't be disposed while the launcher is running
        @SuppressWarnings("resource")
        LauncherClassLoader loader = new LauncherClassLoader(urls);

        //run it      
        Class<?> launcherFrame = loader.loadClass("net.minecraft.LauncherFrame");
        launcherFrame.getMethod("main", String[].class).invoke(null, (Object) args);
    } catch (Exception e) {
        // there's nothing we can do in that case but notify the dev
        e.printStackTrace();
    }
}

From source file:com.heliosdecompiler.appifier.Appifier.java

public static void main(String[] args) throws Throwable {
    if (args.length == 0) {
        System.out.println("An input JAR must be specified");
        return;/*from   w  w  w  .  j a v  a  2 s. c o  m*/
    }

    File in = new File(args[0]);

    if (!in.exists()) {
        System.out.println("Input not found");
        return;
    }

    String outName = args[0];
    outName = outName.substring(0, outName.length() - ".jar".length()) + "-appified.jar";

    File out = new File(outName);

    if (out.exists()) {
        if (!out.delete()) {
            System.out.println("Could not delete out file");
            return;
        }
    }

    try (ZipOutputStream outstream = new ZipOutputStream(new FileOutputStream(out));
            ZipFile zipFile = new ZipFile(in)) {

        {
            ZipEntry systemHook = new ZipEntry("com/heliosdecompiler/appifier/SystemHook.class");
            outstream.putNextEntry(systemHook);
            outstream.write(SystemHookDump.dump());
            outstream.closeEntry();
        }

        Enumeration<? extends ZipEntry> enumeration = zipFile.entries();

        while (enumeration.hasMoreElements()) {
            ZipEntry next = enumeration.nextElement();

            if (!next.isDirectory()) {
                ZipEntry result = new ZipEntry(next.getName());
                outstream.putNextEntry(result);
                if (next.getName().endsWith(".class")) {
                    byte[] classBytes = IOUtils.toByteArray(zipFile.getInputStream(next));
                    outstream.write(transform(classBytes));
                } else {
                    IOUtils.copy(zipFile.getInputStream(next), outstream);
                }
                outstream.closeEntry();
            }
        }
    }
}

From source file:cc.twittertools.corpus.demo.ReadStatuses.java

@SuppressWarnings("static-access")
public static void main(String[] args) throws Exception {
    Options options = new Options();
    options.addOption(OptionBuilder.withArgName("path").hasArg().withDescription("input directory or file")
            .create(INPUT_OPTION));//  w w w.  j a  v a 2  s .com
    options.addOption(VERBOSE_OPTION, false, "print logging output every 10000 tweets");
    options.addOption(DUMP_OPTION, false, "dump statuses");

    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(INPUT_OPTION)) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(ReadStatuses.class.getName(), options);
        System.exit(-1);
    }

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

    StatusStream stream;
    // Figure out if we're reading from HTML SequenceFiles or JSON.
    File file = new File(cmdline.getOptionValue(INPUT_OPTION));
    if (!file.exists()) {
        System.err.println("Error: " + file + " does not exist!");
        System.exit(-1);
    }

    if (file.isDirectory()) {
        stream = new JsonStatusCorpusReader(file);
    } else {
        stream = new JsonStatusBlockReader(file);
    }

    int cnt = 0;
    Status status;
    while ((status = stream.next()) != null) {
        if (cmdline.hasOption(DUMP_OPTION)) {
            String text = status.getText();
            if (text != null) {
                text = text.replaceAll("\\s+", " ");
                text = text.replaceAll("\0", "");
            }
            out.println(String.format("%d\t%s\t%s\t%s", status.getId(), status.getScreenname(),
                    status.getCreatedAt(), text));
        }
        cnt++;
        if (cnt % 10000 == 0 && cmdline.hasOption(VERBOSE_OPTION)) {
            LOG.info(cnt + " statuses read");
        }
    }
    stream.close();
    LOG.info(String.format("Total of %s statuses read.", cnt));
}

From source file:edu.ur.ir.index.DefaultExcelXmlTextExtractor.java

public static void main(String[] args) throws Exception {
    if (args.length <= 0) {
        System.out.println("Must have a file name with full path");
    } else {/*www .j  a  va  2s  .  c  o m*/
        File f = new File(args[0]);
        System.out.println("File exists = " + f.exists());
        DefaultExcelXmlTextExtractor extractor = new DefaultExcelXmlTextExtractor();
        extractor.getText(f);
    }
}

From source file:edu.ur.ir.index.DefaultPowerPointXmlTextExtractor.java

public static void main(String[] args) throws Exception {
    if (args.length <= 0) {
        System.out.println("Must have a file name with full path");
    } else {/*from  w  w  w.j  a  v a2  s . c  o  m*/
        File f = new File(args[0]);
        System.out.println("File exists = " + f.exists());
        DefaultPowerPointXmlTextExtractor extractor = new DefaultPowerPointXmlTextExtractor();
        extractor.getText(f);
    }
}

From source file:edu.ur.ir.index.DefaultWordXmlTextExtractor.java

public static void main(String[] args) throws Exception {
    if (args.length <= 0) {
        System.out.println("Must have a file name with full path");
    } else {/* ww w  .  ja  v  a 2  s  .  c  om*/
        File f = new File(args[0]);
        System.out.println("File exists = " + f.exists());
        DefaultWordXmlTextExtractor extractor = new DefaultWordXmlTextExtractor();
        extractor.getText(f);
    }
}