Example usage for java.io PrintWriter close

List of usage examples for java.io PrintWriter close

Introduction

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

Prototype

public void close() 

Source Link

Document

Closes the stream and releases any system resources associated with it.

Usage

From source file:PrintWriterDemo.java

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

    PrintWriter pw = new PrintWriter(System.out);

    // Experiment with some methods
    pw.println(true);/*from   w  w  w  .j  ava 2 s .co  m*/
    pw.println('A');
    pw.println(500);
    pw.println(40000L);
    pw.println(45.67f);
    pw.println(45.67);
    pw.println("Hello");
    pw.println(new Integer("99"));

    // Close print writer
    pw.close();
}

From source file:com.norconex.collector.http.HttpCollector.java

/**
 * Invokes the HTTP Collector from the command line.  
 * @param args Invoke it once without any arguments to get a 
 *    list of command-line options./*from   ww  w .  j a v  a 2s.  c o m*/
 */
public static void main(String[] args) {
    CommandLine cmd = parseCommandLineArguments(args);
    String action = cmd.getOptionValue(ARG_ACTION);
    File configFile = new File(cmd.getOptionValue(ARG_CONFIG));
    File varFile = null;
    if (cmd.hasOption(ARG_VARIABLES)) {
        varFile = new File(cmd.getOptionValue(ARG_VARIABLES));
    }

    try {
        HttpCollector conn = new HttpCollector(configFile, varFile);
        if (ARG_ACTION_START.equalsIgnoreCase(action)) {
            conn.crawl(false);
        } else if (ARG_ACTION_RESUME.equalsIgnoreCase(action)) {
            conn.crawl(true);
        } else if (ARG_ACTION_STOP.equalsIgnoreCase(action)) {
            conn.stop();
        }
    } catch (Exception e) {
        File errorFile = new File("./error-" + System.currentTimeMillis() + ".log");
        System.err.println("\n\nAn ERROR occured:\n\n" + e.getLocalizedMessage());
        System.err.println(
                "\n\nDetails of the error has been stored at: " + errorFile.getAbsolutePath() + "\n\n");
        try {
            PrintWriter w = new PrintWriter(errorFile);
            e.printStackTrace(w);
            w.flush();
            w.close();
        } catch (FileNotFoundException e1) {
            throw new HttpCollectorException("Cannot write error file.", e1);
        }
    }
}

From source file:Main.java

public static void main(String[] args) {
    String s = "tutorial from java2s.com ";
    try {//from w  w w.jav a 2s.co  m

        PrintWriter pw = new PrintWriter(System.out);

        // append the sequence
        pw.append(s);

        // flush the writer
        pw.flush();

        // print another string
        pw.println("This is an example");

        // flush the writer again
        pw.flush();

        // close the writer
        pw.close();

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

From source file:CompileSourceInMemory.java

public static void main(String args[]) throws IOException {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();

    StringWriter writer = new StringWriter();
    PrintWriter out = new PrintWriter(writer);
    out.println("public class HelloWorld {");
    out.println("  public static void main(String args[]) {");
    out.println("    System.out.println(\"This is in another java file\");");
    out.println("  }");
    out.println("}");
    out.close();
    JavaFileObject file = new JavaSourceFromString("HelloWorld", writer.toString());

    Iterable<? extends JavaFileObject> compilationUnits = Arrays.asList(file);
    CompilationTask task = compiler.getTask(null, null, diagnostics, null, null, compilationUnits);

    boolean success = task.call();
    for (Diagnostic diagnostic : diagnostics.getDiagnostics()) {
        System.out.println(diagnostic.getCode());
        System.out.println(diagnostic.getKind());
        System.out.println(diagnostic.getPosition());
        System.out.println(diagnostic.getStartPosition());
        System.out.println(diagnostic.getEndPosition());
        System.out.println(diagnostic.getSource());
        System.out.println(diagnostic.getMessage(null));

    }//from w ww .  j av  a  2 s. c o  m
    System.out.println("Success: " + success);

    if (success) {
        try {
            Class.forName("HelloWorld").getDeclaredMethod("main", new Class[] { String[].class }).invoke(null,
                    new Object[] { null });
        } catch (ClassNotFoundException e) {
            System.err.println("Class not found: " + e);
        } catch (NoSuchMethodException e) {
            System.err.println("No such method: " + e);
        } catch (IllegalAccessException e) {
            System.err.println("Illegal access: " + e);
        } catch (InvocationTargetException e) {
            System.err.println("Invocation target: " + e);
        }
    }
}

From source file:SAXCopy.java

static public void main(String[] arg) {
    String infilename = null;/*from   www.  ja va  2 s  .  c  o  m*/
    String outfilename = null;
    if (arg.length == 2) {
        infilename = arg[0];
        outfilename = arg[1];
    } else {
        usage();
    }

    try {
        SAXParserFactory spf = SAXParserFactory.newInstance();
        SAXParser parser = spf.newSAXParser();
        XMLReader reader = parser.getXMLReader();
        reader.setErrorHandler(new MyErrorHandler());
        FileOutputStream fos = new FileOutputStream(outfilename);
        PrintWriter out = new PrintWriter(fos);
        MyCopyHandler duper = new MyCopyHandler(out);
        reader.setContentHandler(duper);
        InputSource is = new InputSource(infilename);
        reader.parse(is);
        out.close();
    } catch (SAXException e) {
        System.exit(1);
    } catch (ParserConfigurationException e) {
        System.err.println(e);
        System.exit(1);
    } catch (IOException e) {
        System.err.println(e);
        System.exit(1);
    }
}

From source file:ca.cutterslade.match.scheduler.Main.java

public static void main(final String[] args) throws InterruptedException {
    final CommandLineParser parser = new PosixParser();
    try {/*from w  ww  .j av a 2s .c  o  m*/
        final CommandLine line = parser.parse(OPTIONS, args);
        final int teams = Integer.parseInt(line.getOptionValue('t'));
        final int tiers = Integer.parseInt(line.getOptionValue('r'));
        final int gyms = Integer.parseInt(line.getOptionValue('g'));
        final int courts = Integer.parseInt(line.getOptionValue('c'));
        final int times = Integer.parseInt(line.getOptionValue('m'));
        final int days = Integer.parseInt(line.getOptionValue('d'));
        final int size = Integer.parseInt(line.getOptionValue('z'));
        final Configuration config;
        if (line.hasOption("random"))
            config = Configuration.RANDOM_CONFIGURATION;
        else
            config = new Configuration(ImmutableMap.<SadFaceFactor, Integer>of(),
                    line.hasOption("randomMatches"), line.hasOption("randomSlots"),
                    line.hasOption("randomDays"));
        final Scheduler s = new Scheduler(config, teams, tiers, gyms, courts, times, days, size);
        System.out.println(summary(s));
    } catch (final ParseException e) {
        final HelpFormatter f = new HelpFormatter();
        final PrintWriter pw = new PrintWriter(System.err);
        f.printHelp(pw, 80, "match-scheduler", null, OPTIONS, 2, 2, null, true);
        pw.println(
                "For example: match-scheduler -t 48 -r 3 -d 12 -m 2 -g 3 -c 2 -z 4 --randomMatches --randomSlots");
        pw.close();
    }
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    String filename = "fileName.txt";
    String[] linesToWrite = new String[] { "a", "b" };
    boolean appendToFile = true;

    PrintWriter pw = null;
    if (appendToFile) {
        pw = new PrintWriter(new FileWriter(filename, true));
    } else {// w w  w  . j  a  va  2 s.  com
        pw = new PrintWriter(new FileWriter(filename));
        // pw = new PrintWriter(new FileWriter(filename, false));
    }
    for (int i = 0; i < linesToWrite.length; i++) {
        pw.println(linesToWrite[i]);
    }
    pw.flush();
    pw.close();
}

From source file:com.opengamma.integration.marketdata.WatchListRecorder.java

/**
 * Main entry point.// w  w w. j a  v a 2  s .c om
 * 
 * @param args the arguments
 * @throws Exception if an error occurs
 */
public static void main(final String[] args) throws Exception { // CSIGNORE
    final CommandLineParser parser = new PosixParser();
    final Options options = new Options();
    final Option outputFileOpt = new Option("o", "output", true, "output file");
    outputFileOpt.setRequired(true);
    options.addOption(outputFileOpt);
    final Option urlOpt = new Option("u", "url", true, "server url");
    options.addOption(urlOpt);
    String outputFile = "watchList.txt";
    String url = "http://localhost:8080/jax";
    try {
        final CommandLine cmd = parser.parse(options, args);
        outputFile = cmd.getOptionValue("output");
        url = cmd.getOptionValue("url");
    } catch (final ParseException exp) {
        s_logger.error("Option parsing failed: {}", exp.getMessage());
        System.exit(0);
    }

    final WatchListRecorder recorder = create(URI.create(url), "main", "combined");
    recorder.addWatchScheme(ExternalSchemes.BLOOMBERG_TICKER);
    recorder.addWatchScheme(ExternalSchemes.BLOOMBERG_BUID);
    final PrintWriter pw = new PrintWriter(outputFile);
    recorder.setPrintWriter(pw);
    recorder.run();

    pw.close();
    System.exit(0);
}

From source file:MainClass.java

public static void main(String[] args) throws Exception {
    String hostname = "localhost";

    Socket theSocket = new Socket(hostname, 7);
    BufferedReader networkIn = new BufferedReader(new InputStreamReader(theSocket.getInputStream()));
    BufferedReader userIn = new BufferedReader(new InputStreamReader(System.in));
    PrintWriter out = new PrintWriter(theSocket.getOutputStream());
    System.out.println("Connected to echo server");

    while (true) {
        String theLine = userIn.readLine();
        if (theLine.equals("."))
            break;
        out.println(theLine);//  w ww  .j  a  va  2s  . c  o  m
        out.flush();
        System.out.println(networkIn.readLine());
    }
    networkIn.close();
    out.close();
}

From source file:MainClass.java

public static void main(String args[]) {

    try {/*from   www.ja v  a2 s  . c om*/
        PrintWriter pw = new PrintWriter(System.out);

        // Experiment with some methods
        pw.println(true);
        pw.println('A');
        pw.println(500);
        pw.println(40000L);
        pw.println(45.67f);
        pw.println(45.67);
        pw.println("Hello");
        pw.println(new Integer("99"));

        // Close print writer
        pw.close();
    } catch (Exception e) {
        System.out.println("Exception: " + e);
    }
}