Example usage for java.io PrintStream PrintStream

List of usage examples for java.io PrintStream PrintStream

Introduction

In this page you can find the example usage for java.io PrintStream PrintStream.

Prototype

public PrintStream(OutputStream out, boolean autoFlush, Charset charset) 

Source Link

Document

Creates a new print stream, with the specified OutputStream, automatic line flushing and charset.

Usage

From source file:cc.twittertools.search.local.SearchStatuses.java

@SuppressWarnings("static-access")
public static void main(String[] args) throws Exception {
    Options options = new Options();
    options.addOption(//from  w w  w . ja  v  a  2 s  . c o m
            OptionBuilder.withArgName("path").hasArg().withDescription("index location").create(INDEX_OPTION));
    options.addOption(
            OptionBuilder.withArgName("string").hasArg().withDescription("query id").create(QID_OPTION));
    options.addOption(
            OptionBuilder.withArgName("string").hasArg().withDescription("query text").create(QUERY_OPTION));
    options.addOption(
            OptionBuilder.withArgName("string").hasArg().withDescription("runtag").create(RUNTAG_OPTION));
    options.addOption(OptionBuilder.withArgName("num").hasArg().withDescription("maxid").create(MAX_ID_OPTION));
    options.addOption(OptionBuilder.withArgName("num").hasArg().withDescription("number of results to return")
            .create(NUM_RESULTS_OPTION));
    options.addOption(OptionBuilder.withArgName("similarity").hasArg()
            .withDescription("similarity to use (BM25, LM)").create(SIMILARITY_OPTION));
    options.addOption(new Option(VERBOSE_OPTION, "print out complete document"));

    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)) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(SearchStatuses.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 qid = cmdline.hasOption(QID_OPTION) ? cmdline.getOptionValue(QID_OPTION) : DEFAULT_QID;
    String queryText = cmdline.hasOption(QUERY_OPTION) ? cmdline.getOptionValue(QUERY_OPTION) : DEFAULT_Q;
    String runtag = cmdline.hasOption(RUNTAG_OPTION) ? cmdline.getOptionValue(RUNTAG_OPTION) : DEFAULT_RUNTAG;
    long maxId = cmdline.hasOption(MAX_ID_OPTION) ? Long.parseLong(cmdline.getOptionValue(MAX_ID_OPTION))
            : DEFAULT_MAX_ID;
    int numResults = cmdline.hasOption(NUM_RESULTS_OPTION)
            ? Integer.parseInt(cmdline.getOptionValue(NUM_RESULTS_OPTION))
            : DEFAULT_NUM_RESULTS;
    boolean verbose = cmdline.hasOption(VERBOSE_OPTION);

    String similarity = "LM";
    if (cmdline.hasOption(SIMILARITY_OPTION)) {
        similarity = cmdline.getOptionValue(SIMILARITY_OPTION);
    }

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

    IndexReader reader = DirectoryReader.open(FSDirectory.open(indexLocation));
    IndexSearcher searcher = new IndexSearcher(reader);

    if (similarity.equalsIgnoreCase("BM25")) {
        searcher.setSimilarity(new BM25Similarity());
    } else if (similarity.equalsIgnoreCase("LM")) {
        searcher.setSimilarity(new LMDirichletSimilarity(2500.0f));
    }

    QueryParser p = new QueryParser(Version.LUCENE_43, IndexStatuses.StatusField.TEXT.name,
            IndexStatuses.ANALYZER);
    Query query = p.parse(queryText);
    Filter filter = NumericRangeFilter.newLongRange(StatusField.ID.name, 0L, maxId, true, true);

    TopDocs rs = searcher.search(query, filter, numResults);

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

        out.println(String.format("%s Q0 %s %d %f %s", qid, hit.getField(StatusField.ID.name).numericValue(), i,
                scoreDoc.score, runtag));
        if (verbose) {
            out.println("# " + hit.toString().replaceAll("[\\n\\r]+", " "));
        }
        i++;
    }

    reader.close();
    out.close();
}

From source file:is.merkor.cli.Main.java

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

    List<String> results = new ArrayList<String>();

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

    CommandLineParser parser = new GnuParser();
    try {//from w  w w  .  j  av  a 2s  .com

        MerkorCommandLineOptions.createOptions();
        results = processCommandLine(parser.parse(MerkorCommandLineOptions.options, args));
        //          out.print("\n");
        //          for (String str : results) {
        //             if(!str.equals("no message"))
        //                out.println(str);
        //         }
        //          out.print("\n");
        //         if (results.isEmpty()) {   
        //            out.println("nothing found for parameters: ");
        //            for (int i = 0; i < args.length; i++)
        //               out.println("\t" + args[i]);
        //            out.println("for help type: -help or see README.markdown");
        //            out.print("\n");
        //         }
    } catch (ParseException e) {
        System.err.println("Parsing failed.  Reason: " + e.getMessage());
    }
}

From source file:Main.java

public static void save(String filename, Document document) throws IOException {
    PrintStream out = null;//from w w  w .  j ava2  s .co  m
    try {
        out = new PrintStream(new BufferedOutputStream(new FileOutputStream(filename)), true, "UTF-8");
        //traceNode(document, "");
        print(out, document);
    } catch (Exception ex) {
        throw new IOException(ex.getLocalizedMessage());
    } finally {
        if (out != null)
            try {
                out.close();
            } catch (Exception e) {
                // ignore
            }
    }
}

From source file:Main.java

public static byte[] getContents(Document document) throws IOException {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    try {// ww w. j  a v a 2  s  . c o m
        print(new PrintStream(out, true, "UTF-8"), document);
        return out.toByteArray();
    } catch (Exception ex) {
        throw new IOException(ex.getLocalizedMessage());
    } finally {
        if (out != null)
            try {
                out.close();
            } catch (Exception e) {
                // ignore
            }
    }
}

From source file:com.sap.prd.mobile.ios.mios.XCodeVersionUtil.java

public static String getXCodeVersionString() throws XCodeException {
    PrintStream out = null;//from w w  w . ja  v a  2s  .  c o m
    try {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        out = new PrintStream(bos, true, Charset.defaultCharset().name());
        int exitCode = Forker.forkProcess(out, new File("."), new String[] { "xcodebuild", "-version" });
        if (exitCode == 0) {
            return bos.toString(Charset.defaultCharset().name());
        } else {
            throw new XCodeException("Could not get xcodebuild version (exit code = " + exitCode + ")");
        }
    } catch (Exception e) {
        throw new XCodeException("Could not get xcodebuild version");
    } finally {
        IOUtils.closeQuietly(out);
    }
}

From source file:Main.java

public static void save(String filename, Document document) throws IOException {
    PrintStream out = null;//from w w w .j a  v  a2 s . c o  m
    try {
        out = new PrintStream(new BufferedOutputStream(new FileOutputStream(filename)), true, "UTF-8");
        // traceNode(document, "");
        print(out, document);
    } catch (Exception ex) {
        throw new IOException(ex.getLocalizedMessage());
    } finally {
        if (out != null)
            try {
                out.close();
            } catch (Exception e) {
                // ignore
            }
    }
}

From source file:com.meltmedia.dropwizard.crypto.Mocks.java

public static Callable<String> mockOutput(Namespace namespace) throws UnsupportedEncodingException {
    final ByteArrayOutputStream out = new ByteArrayOutputStream();
    when(namespace.get(Commands.OUTFILE)).thenReturn(new PrintStream(out, true, "UTF-8"));
    return new Callable<String>() {
        @Override/* w w w. j a  v  a2s. c  om*/
        public String call() throws Exception {
            return out.toString("UTF-8");
        }
    };
}

From source file:fi.jumi.core.stdout.OutputCapturer.java

private static PrintStream createNonSynchronizedPrintStream(OutputStream out, Charset charset) {
    try {//from  w  w w.j  a  v  a 2  s .c  o m
        return new PrintStream(out, false, charset.name());
    } catch (UnsupportedEncodingException e) {
        throw Boilerplate.rethrow(e);
    }
}

From source file:Main.java

public static void save(String filename, Node node) throws IOException {
    PrintStream out = null;/* ww  w.  ja v  a2  s . co m*/
    try {
        out = new PrintStream(new BufferedOutputStream(new FileOutputStream(filename)), true, "UTF-8");
        print(out, node);
    } catch (Exception ex) {
        throw new IOException(ex.getLocalizedMessage());
    } finally {
        if (out != null)
            try {
                out.close();
            } catch (Exception e) {
                // ignore
            }
    }
}

From source file:com.javacreed.examples.akka.internal.FileGreetingService.java

@Override
public void greet(final Subject subject) {
    FileGreetingService.LOGGER.debug("Greeting: {}", subject);
    try (PrintStream out = new PrintStream(new FileOutputStream("greetings.txt", true), true, "UTF-8")) {
        out.printf("[%tF %<tT.%<tL] Hello %s%n", System.currentTimeMillis(), subject.getName());
    } catch (final IOException e) {
        FileGreetingService.LOGGER.error("Failed to greet: {}", subject, e);
    }/*from w ww  .  java  2 s  .c o  m*/
}