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(File file, Charset charset) throws IOException 

Source Link

Document

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

Usage

From source file:Main.java

public static void main(String[] args) {
    byte c = 70;//from   w w w . j a  va 2s  . com

    PrintStream ps = new PrintStream(System.out, true);

    // write byte c which is character F in ASCII
    ps.write(c);

    // flush the stream
    ps.flush();

}

From source file:Main.java

public static void main(String[] args) throws Exception {
    byte c = 70;/*  w  w w.j  a  v  a  2  s .  c o  m*/
    PrintStream ps = new PrintStream("c:/text.txt", "UTF8");

    // write byte c which is character F in ASCII
    ps.write(c);

    // flush the stream
    ps.flush();

}

From source file:Main.java

public static void main(String[] args) throws Exception {
    byte c = 70;/* ww w.  j av  a 2 s  .  com*/
    PrintStream ps = new PrintStream(new File("c:/text.txt"), "ASCII");

    // write byte c which is character F in ASCII
    ps.write(c);

    // flush the stream
    ps.flush();
    ps.close();
}

From source file:com.jbrisbin.groovy.mqdsl.RabbitMQDsl.java

public static void main(String[] argv) {

    // Parse command line arguments
    CommandLine args = null;/*from  w  ww.  ja  va  2s .  co m*/
    try {
        Parser p = new BasicParser();
        args = p.parse(cliOpts, argv);
    } catch (ParseException e) {
        log.error(e.getMessage(), e);
    }

    // Check for help
    if (args.hasOption('?')) {
        printUsage();
        return;
    }

    // Runtime properties
    Properties props = System.getProperties();

    // Check for ~/.rabbitmqrc
    File userSettings = new File(System.getProperty("user.home"), ".rabbitmqrc");
    if (userSettings.exists()) {
        try {
            props.load(new FileInputStream(userSettings));
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
    }

    // Load Groovy builder file
    StringBuffer script = new StringBuffer();
    BufferedInputStream in = null;
    String filename = "<STDIN>";
    if (args.hasOption("f")) {
        filename = args.getOptionValue("f");
        try {
            in = new BufferedInputStream(new FileInputStream(filename));
        } catch (FileNotFoundException e) {
            log.error(e.getMessage(), e);
        }
    } else {
        in = new BufferedInputStream(System.in);
    }

    // Read script
    if (null != in) {
        byte[] buff = new byte[4096];
        try {
            for (int read = in.read(buff); read > -1;) {
                script.append(new String(buff, 0, read));
                read = in.read(buff);
            }
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
    } else {
        System.err.println("No script file to evaluate...");
    }

    PrintStream stdout = System.out;
    PrintStream out = null;
    if (args.hasOption("o")) {
        try {
            out = new PrintStream(new FileOutputStream(args.getOptionValue("o")), true);
            System.setOut(out);
        } catch (FileNotFoundException e) {
            log.error(e.getMessage(), e);
        }
    }

    String[] includes = (System.getenv().containsKey("MQDSL_INCLUDE")
            ? System.getenv("MQDSL_INCLUDE").split(String.valueOf(File.pathSeparatorChar))
            : new String[] { System.getenv("HOME") + File.separator + ".mqdsl.d" });

    try {
        // Setup RabbitMQ
        String username = (args.hasOption("U") ? args.getOptionValue("U")
                : props.getProperty("mq.user", "guest"));
        String password = (args.hasOption("P") ? args.getOptionValue("P")
                : props.getProperty("mq.password", "guest"));
        String virtualHost = (args.hasOption("v") ? args.getOptionValue("v")
                : props.getProperty("mq.virtualhost", "/"));
        String host = (args.hasOption("h") ? args.getOptionValue("h")
                : props.getProperty("mq.host", "localhost"));
        int port = Integer.parseInt(
                args.hasOption("p") ? args.getOptionValue("p") : props.getProperty("mq.port", "5672"));

        CachingConnectionFactory connectionFactory = new CachingConnectionFactory(host);
        connectionFactory.setPort(port);
        connectionFactory.setUsername(username);
        connectionFactory.setPassword(password);
        if (null != virtualHost) {
            connectionFactory.setVirtualHost(virtualHost);
        }

        // The DSL builder
        RabbitMQBuilder builder = new RabbitMQBuilder();
        builder.setConnectionFactory(connectionFactory);
        // Our execution environment
        Binding binding = new Binding(args.getArgs());
        binding.setVariable("mq", builder);
        String fileBaseName = filename.replaceAll("\\.groovy$", "");
        binding.setVariable("log",
                LoggerFactory.getLogger(fileBaseName.substring(fileBaseName.lastIndexOf("/") + 1)));
        if (null != out) {
            binding.setVariable("out", out);
        }

        // Include helper files
        GroovyShell shell = new GroovyShell(binding);
        for (String inc : includes) {
            File f = new File(inc);
            if (f.isDirectory()) {
                File[] files = f.listFiles(new FilenameFilter() {
                    @Override
                    public boolean accept(File file, String s) {
                        return s.endsWith(".groovy");
                    }
                });
                for (File incFile : files) {
                    run(incFile, shell, binding);
                }
            } else {
                run(f, shell, binding);
            }
        }

        run(script.toString(), shell, binding);

        while (builder.isActive()) {
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                log.error(e.getMessage(), e);
            }
        }

        if (null != out) {
            out.close();
            System.setOut(stdout);
        }

    } finally {
        System.exit(0);
    }
}

From source file:ca.ualberta.exemplar.core.Exemplar.java

public static void main(String[] rawArgs) throws FileNotFoundException, UnsupportedEncodingException {

    CommandLineParser cli = new BasicParser();

    Options options = new Options();
    options.addOption("h", "help", false, "shows this message");
    options.addOption("b", "benchmark", true, "expects input to be a benchmark file (type = binary | nary)");
    options.addOption("p", "parser", true, "defines which parser to use (parser = stanford | malt)");

    CommandLine line = null;/*from   w ww .j a v  a 2 s  .  c  om*/

    try {
        line = cli.parse(options, rawArgs);
    } catch (ParseException exp) {
        System.err.println(exp.getMessage());
        System.exit(1);
    }

    String[] args = line.getArgs();
    String parserName = line.getOptionValue("parser", "malt");

    if (line.hasOption("help")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("sh ./exemplar", options);
        System.exit(0);
    }

    if (args.length != 2) {
        System.out.println("error: exemplar requires an input file and output file.");
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("sh ./exemplar <input> <output>", options);
        System.exit(0);
    }

    File input = new File(args[0]);
    File output = new File(args[1]);

    String benchmarkType = line.getOptionValue("benchmark", "");
    if (!benchmarkType.isEmpty()) {
        if (benchmarkType.equals("binary")) {
            BenchmarkBinary evaluation = new BenchmarkBinary(input, output, parserName);
            evaluation.runAndTime();
            System.exit(0);
        } else {
            if (benchmarkType.equals("nary")) {
                BenchmarkNary evaluation = new BenchmarkNary(input, output, parserName);
                evaluation.runAndTime();
                System.exit(0);
            } else {
                System.out.println("error: benchmark option has to be either 'binary' or 'nary'.");
                System.exit(0);
            }
        }
    }

    Parser parser = null;
    if (parserName.equals("stanford")) {
        parser = new ParserStanford();
    } else {
        if (parserName.equals("malt")) {
            parser = new ParserMalt();
        } else {
            System.out.println(parserName + " is not a valid parser.");
            System.exit(0);
        }
    }

    System.out.println("Starting EXEMPLAR...");

    RelationExtraction exemplar = null;
    try {
        exemplar = new RelationExtraction(parser);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }

    BlockingQueue<String> inputQueue = new ArrayBlockingQueue<String>(QUEUE_SIZE);
    PlainTextReader reader = null;
    reader = new PlainTextReader(inputQueue, input);

    Thread readerThread = new Thread(reader);
    readerThread.start();

    PrintStream statementsOut = null;

    try {
        statementsOut = new PrintStream(output, "UTF-8");
    } catch (FileNotFoundException e1) {
        e1.printStackTrace();
        System.exit(0);
    } catch (UnsupportedEncodingException e1) {
        e1.printStackTrace();
        System.exit(0);
    }

    statementsOut.println("Subjects\tRelation\tObjects\tNormalized Relation\tSentence");

    while (true) {
        String doc = null;
        try {
            doc = inputQueue.take();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        if (doc.isEmpty()) {
            break;
        }

        List<RelationInstance> instances = exemplar.extractRelations(doc);

        for (RelationInstance instance : instances) {

            // Output SUBJ arguments in a separate field, for clarity
            boolean first = true;
            for (Argument arg : instance.getArguments()) {
                if (arg.argumentType.equals("SUBJ")) {
                    if (first) {
                        first = false;
                    } else {
                        statementsOut.print(",,");
                    }
                    statementsOut.print(arg.argumentType + ":" + arg.entityId);
                }
            }

            // Output the original relation
            statementsOut.print("\t" + instance.getOriginalRelation() + "\t");

            // Output the DOBJ arguments, followed by POBJ
            first = true;
            for (Argument arg : instance.getArguments()) {
                if (arg.argumentType.equals("DOBJ")) {
                    if (first) {
                        first = false;
                    } else {
                        statementsOut.print(",,");
                    }
                    statementsOut.print(arg.argumentType + ":" + arg.entityId);
                }
            }
            for (Argument arg : instance.getArguments()) {
                if (arg.argumentType.startsWith("POBJ")) {
                    if (first) {
                        first = false;
                    } else {
                        statementsOut.print(",,");
                    }
                    statementsOut.print(arg.argumentType + ":" + arg.entityId);
                }
            }
            statementsOut.print("\t" + instance.getNormalizedRelation());
            statementsOut.print("\t" + instance.getSentence());
            statementsOut.println();
        }
    }

    System.out.println("Done!");
    statementsOut.close();

}

From source file:edu.wpi.margrave.MCommunicator.java

public static void main(String[] args) {
    ArrayList<String> foo = new ArrayList<String>();

    Set<String> argsSet = new HashSet<String>();
    for (int ii = 0; ii < args.length; ii++) {
        argsSet.add(args[ii].toLowerCase());
    }//  w w w  .  ja  v  a 2 s.  c  o  m

    if (argsSet.contains("-log")) {
        // parser is in racket now. instead, require -log switch for logging
        //MEnvironment.debugParser = true;
        bDoLogging = true;
    }

    if (argsSet.contains("-min")) {
        bMinimalModels = true;
    }

    // Re-direct all System.err input to our custom buffer
    // Uses Apache Commons IO for WriterOutputStream.
    System.setErr(new PrintStream(new WriterOutputStream(MEnvironment.errorWriter), true));

    // Re-direct all System.out input to our custom buffer.
    // (We have already saved System.out.)
    // This is useful in case we start getting GC messages from SAT4j.
    System.setOut(new PrintStream(new WriterOutputStream(MEnvironment.outWriter), true));

    initializeLog();
    writeToLog("\n\n");

    // Inform the caller that we are ready to receive commands
    sendReadyReply();

    while (true) {
        // Block until a command is received, handle it, and then return the result.
        handleXMLCommand(in);
    }

    // outLog will be closed as it goes out of scope
}

From source file:de.citec.sc.index.ProcessAnchorFile.java

public static void run(String filePath) {

    try {/*w ww.java 2s .  c  om*/
        File file = new File("new.ttl");

        // if file doesnt exists, then create it
        if (file.exists()) {
            file.delete();
            file.createNewFile();
        }
        if (!file.exists()) {
            file.createNewFile();
        }
        BufferedReader wpkg = new BufferedReader(new InputStreamReader(new FileInputStream(filePath), "UTF-8"));
        String line = "";

        PrintStream ps = new PrintStream("new.ttl", "UTF-8");

        while ((line = wpkg.readLine()) != null) {

            String[] data = line.split("\t");

            if (data.length == 3) {
                String label = data[0];

                label = StringEscapeUtils.unescapeJava(label);

                try {
                    label = URLDecoder.decode(label, "UTF-8");
                } catch (Exception e) {
                }

                String uri = data[1].replace("http://dbpedia.org/resource/", "");
                uri = StringEscapeUtils.unescapeJava(uri);

                try {
                    uri = URLDecoder.decode(uri, "UTF-8");
                } catch (Exception e) {
                }

                String f = data[2];

                label = label.toLowerCase();
                ps.println(label + "\t" + uri + "\t" + f);

            }

        }

        wpkg.close();
        ps.close();

        File oldFile = new File(filePath);
        oldFile.delete();
        oldFile.createNewFile();

        file.renameTo(oldFile);

    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.googlecode.psiprobe.tools.LogOutputStream.java

/**
 * Creates a {@code PrintStream} with autoFlush enabled which will write to
 * the given {@code Log} at the given level.
 * /*from   w ww.  j a  v  a 2s.  c  o m*/
 * @param log
 *        the {@code Log} to which to write
 * @param level
 *        the level at which to write
 * @return a {@code PrintStream} that writes to the given log
 */
public static PrintStream createPrintStream(Log log, int level) {
    LogOutputStream logStream = new LogOutputStream(log, level);
    return new PrintStream(logStream, true);
}

From source file:org.aksw.gerbil.web.config.RootConfig.java

protected static void replaceSystemStreams() {
    System.setOut(new PrintStream(new ConsoleLogger(false), true));
    System.setErr(new PrintStream(new ConsoleLogger(true), true));
}

From source file:net.jperf.LogParserTest.java

public void testLogParserMain() throws Exception {
    PrintStream realOut = System.out;
    ByteArrayOutputStream fakeOut = new ByteArrayOutputStream();
    System.setOut(new PrintStream(fakeOut, true));
    try {//from w w w  .java 2  s .c  o  m
        //usage
        realOut.println("-- Usage Test --");
        LogParser.runMain(new String[] { "--help" });
        realOut.println(fakeOut.toString());
        assertTrue(fakeOut.toString().indexOf("Usage") >= 0);
        fakeOut.reset();

        //log on std in, write to std out
        InputStream realIn = System.in;
        ByteArrayInputStream fakeIn = new ByteArrayInputStream(testLog.getBytes());
        System.setIn(fakeIn);
        try {
            realOut.println("-- Std in -> Std out Test --");
            LogParser.runMain(new String[0]);
            realOut.println(fakeOut.toString());
            assertTrue(fakeOut.toString().indexOf("tag") >= 0 && fakeOut.toString().indexOf("tag2") >= 0
                    && fakeOut.toString().indexOf("tag3") >= 0);
            fakeOut.reset();
        } finally {
            System.setIn(realIn);
        }

        //Log from a file
        FileUtils.writeStringToFile(new File("./target/logParserTest.log"), testLog);

        //log from file, write to std out
        realOut.println("-- File in -> Std out Test --");
        LogParser.runMain(new String[] { "./target/logParserTest.log" });
        realOut.println(fakeOut.toString());
        assertTrue(fakeOut.toString().indexOf("tag") >= 0 && fakeOut.toString().indexOf("tag2") >= 0
                && fakeOut.toString().indexOf("tag3") >= 0);
        fakeOut.reset();

        //CSV format test
        realOut.println("-- File in -> Std out Test with CSV --");
        LogParser.runMain(new String[] { "-f", "csv", "./target/logParserTest.log" });
        realOut.println(fakeOut.toString());
        assertTrue(fakeOut.toString().indexOf("\"tag\",") >= 0 && fakeOut.toString().indexOf("\"tag2\",") >= 0
                && fakeOut.toString().indexOf("\"tag3\",") >= 0);
        fakeOut.reset();

        //log from file, write to file
        realOut.println("-- File in -> File out Test --");
        LogParser.runMain(new String[] { "-o", "./target/statistics.out", "./target/logParserTest.log" });
        String statsOut = FileUtils.readFileToString(new File("./target/statistics.out"));
        realOut.println(statsOut);
        assertTrue(
                statsOut.indexOf("tag") >= 0 && statsOut.indexOf("tag2") >= 0 && statsOut.indexOf("tag3") >= 0);

        //log from file, write to file, different timeslice
        realOut.println("-- File in -> File out with different timeslice Test --");
        LogParser.runMain(new String[] { "-o", "./target/statistics.out", "--timeslice", "120000",
                "./target/logParserTest.log" });
        statsOut = FileUtils.readFileToString(new File("./target/statistics.out"));
        realOut.println(statsOut);
        assertTrue(
                statsOut.indexOf("tag") >= 0 && statsOut.indexOf("tag2") >= 0 && statsOut.indexOf("tag3") >= 0);

        //missing param test
        realOut.println("-- Missing param test --");
        assertEquals(1, LogParser.runMain(new String[] { "./target/logParserTest.log", "-o" }));

        //unknown arg test
        realOut.println("-- Unknown arg test --");
        assertEquals(1, LogParser.runMain(new String[] { "./target/logParserTest.log", "--foo" }));
        realOut.println(fakeOut);
        assertTrue(fakeOut.toString().indexOf("Unknown") >= 0);

        //graphing test
        realOut.println("-- File in -> File out with graphing --");
        LogParser.runMain(new String[] { "-o", "./target/statistics.out", "-g", "./target/perfGraphs.out",
                "./src/test/resources/net/jperf/dummyLog.txt" });
        statsOut = FileUtils.readFileToString(new File("./target/statistics.out"));
        realOut.println(statsOut);
        String graphsOut = FileUtils.readFileToString(new File("./target/perfGraphs.out"));
        realOut.println(graphsOut);
        assertTrue(graphsOut.indexOf("chtt=TPS") > 0 && graphsOut.indexOf("chtt=Mean") > 0);
    } finally {
        System.setOut(realOut);
    }
}