PrintWriter

In this chapter you will learn:

  1. How to use PrintWriter
  2. Append to a file with PrintWriter
  3. Turn off the auto flush on PrintWriter
  4. How to extend PrintWriter to create your own Writer

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;
//ja  v a2 s . 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  2  s .  co m*/
A
500
40000
45.67
45.67
Hello
99

Append to a file with PrintWriter

The following code writes lines of text to file using a PrintWriter. It uses a boolean value to control if to append to the file.

import java.io.FileWriter;
import java.io.PrintWriter;
/*from   j  a  va 2s.co  m*/
public class Main {
  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 {
      pw = new PrintWriter(new FileWriter(filename));
    }
    for (int i = 0; i < linesToWrite.length; i++) {
      pw.println(linesToWrite[i]);
    }
    pw.flush();
    pw.close();
  }
}

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;
/*from   ja  v  a2  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);
    }
  }
}

extends PrintWriter

The following code has a PrintWriter that ends lines with a carriage return-line feed (CRLF).

/*//from  j  av a 2  s.  c  o m
 * JBoss, Home of Professional Open Source
 * Copyright 2005, JBoss Inc., and individual contributors as indicated
 * by the @authors tag. See the copyright.txt in the distribution for a
 * full listing of individual contributors.
 *
 * This is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 */

import java.io.IOException;
import java.io.InterruptedIOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Writer;

/**
 * A <tt>PrintWriter</tt> that ends lines with a carriage return-line feed (<tt>CRLF</tt>).
 * 
 * <h3>Concurrency</h3>
 * This class is <b>as</b> synchronized as <tt>PrintWriter</tt>.
 * 
 * @version <tt>$Revision: 1958 $</tt>
 * @author <a href="mailto:jason@planet57.com">Jason Dillon</a>
 */
public class CRLFPrintWriter extends PrintWriter {
  protected boolean autoFlush = false;

  public CRLFPrintWriter(final Writer out) {
    super(out);
  }

  public CRLFPrintWriter(final Writer out, final boolean autoFlush) {
    super(out, autoFlush);
    this.autoFlush = autoFlush;
  }

  public CRLFPrintWriter(final OutputStream out) {
    super(out);
  }

  public CRLFPrintWriter(final OutputStream out, final boolean autoFlush) {
    super(out, autoFlush);
    this.autoFlush = autoFlush;
  }

  protected void ensureOpen() throws IOException {
    if (out == null)
      throw new IOException("Stream closed");
  }

  public void println() {
    try {
      synchronized (lock) {
        ensureOpen();

        out.write("\r\n");

        if (autoFlush) {
          out.flush();
        }
      }
    } catch (InterruptedIOException e) {
      Thread.currentThread().interrupt();
    } catch (IOException e) {
      setError();
    }
  }
}

Next chapter...

What you will learn in the next chapter:

  1. How to use OutputStreamWriter
Home » Java Tutorial » Reader Writer
Stream vs Reader and writer
InputStream
FileInputStream
ObjectInputStream
DataInputStream
BufferedInputStream
SequenceInputStream
PushbackInputStream
ByteArrayInputStream
PrintStream
OutputStream
FileOutputStream
DataOutputStream
ObjectOutputStream
BufferedOutputStream
ByteArrayOutputStream
FilterOutputStream
Reader
FileReader
BufferedReader
CharArrayReader
StringReader
LineNumberReader
InputStreamReader
PushbackReader
Writer
FileWriter
BufferedWriter
CharArrayWriter
StringWriter
PrintWriter
OutputStreamWriter