PrintWriter

In this chapter you will learn:

  1. How to use PrintWriter
  2. Turn off the auto flush on PrintWriter

Use PrintWriter

PrintWriter is a character-oriented version of PrintStream. It implements the Appendable, Closeable, and Flushable interfaces.

PrintWriter has several constructors.

PrintWriter supports the print() and println() methods for all types, including Object. If an argument is not a primitive type, the PrintWriter methods will call the object's toString() method and then output the result.

PrintWriter supports the printf() method which accepts the precise format of the data.

PrintWriter printf(String fmtString, Object ... args) 
PrintWriter printf(Locale loc, String fmtString, Object ... args)

The first version writes args to standard output in the format specified by fmtString, using the default locale.

The following code creates PrintWriter from System.out

import java.io.PrintWriter;
//from j av a  2s  .c  o m
public class Main {

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

    PrintWriter pw = new PrintWriter(System.out);

    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"));

    pw.close();
  }
}

The output:

true/*from j av a 2s . co  m*/
A
500
40000
45.67
45.67
Hello
99

Turn off the auto flush on PrintWriter

The following code turns off the auto flush on PrintWriter.

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.PrintWriter;
/*  j  ava2  s. c  o  m*/
public class MainClass {

  public static void main(String args[]) {

    try {

      // Create a print writer
      FileWriter fw = new FileWriter(args[0]);
      BufferedWriter bw = new BufferedWriter(fw);
      PrintWriter pw = new PrintWriter(bw, false);

      // 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);
    }
  }
}

Next chapter...

What you will learn in the next chapter:

  1. How to use OutputStreamWriter