PrintWriter class

 

                  See Writer class for descriptions of PrintWriter's inherited methods.  They are:

 

.close( )                                    Closes the stream, flushing it first.

.flush( )                                    Flushes all associated buffers in a stream without closing it.

.write( int c )                             Writes a single char, supplied as the low-order two bytes of a four-byte int.

.write( char[ ] c )                       Writes an array of characters.

.write( char[ ] c, int off, int len )  Writes a portion len of a character array, beginning at offset

.write( String s )                        Writes a String.

.write( String s, int off, int len )  Writes a portion len of a String, beginning at off

 

plus more below.

 

See BufferedWriter class for examples of using PrintWriter with buffering.

 

 

  The PrintWriter class extends Writer and provides twenty-one new methods for writing or displaying character text representations of Java primitive data types. Most notable are the handy print(...) and println(...) methods.

 

  You are supposed to use (the newer) PrintWriter instead of PrintStream to put out readable text bytes.  PrintWriter has all of PrintStream’s print output methods.  (However, since System.out was created as a PrintStream, you must continue to use PrintStream's methods when you say System.out.print(...) or System.out.println(...).)

 

  PrintWriter needs an actual Writer output stream chained to it to write to the sink.  This is usually a FileWriter or a FileOutputStream.  i.e.

 

import java.io.*;

 

PrintWriter pw = new PrintWriter( new FileOutputStream( "myoutputfile",  true ));

pw.println( "Mary had a little lamb." );

pw.flush( );

 

 

  PrintWriter constructors will take a Writer stream, which writes characters, or they will take an OutputStream, which writes bytes.  Furthermore, the fact that it will accept a Writer stream means it will take an OutputStreamWriter.  This is a stream which allows you to specify a specific character encoding in its constructor.  By manipulating this chaining you can use effectively use PrintWriter's handy print(...) and println(...) methods to create any type of file. i.e.

 

PrintWriter pw = new PrintWriter( new OutputStreamWriter( new FileOutputStream( "newasciifile", true ), "US-ASCII" )); 

will write ASCII bytes with PrintWriter's print(...) and println(...) methods

 

PrintWriter pw = new PrintWriter( new OutputStreamWriter( new FileOutputStream( "newUTF8file", true ), "UTF-8" )); 

will write Unicode characters in UTF-8 format

 

PrintWriter pw = new PrintWriter( new OutputStreamWriter( new FileOutputStream( "newUTF16file", true ), "UTF-16" )); 

will write Unicode characters in UTF-16 format.

Note that the presence of 16-bit characters will now double the normal file size.

 

PrintWriter pw = new PrintWriter( new FileOutputStream( "newregularfile",  true )); 

will simply write a byte file in the machine's default encoding, such as cp2552 for Windows.

 

 

  Most importantly, you don't need a second parameter to use a buffered  FileWriter to write a character file in the machine's default encoding:

 

PrintWriter pw = new PrintWriter( new BufferedWriter( new FileWriter( "mynewcharfile" ))); 

 

 All of PrintWriter's print(...) and println(...) methods invoke toString( ) on the argument to be printed.

 

 Here are the 21 methods added to Writer’s by PrintWriter:

 

checkError( ) - Flush the stream if it is not closed and check its error state.  Note that, if an error does occur and checkError( ) returns false, you cannot reset it without closing the stream.

setError( ) - Indicate that an error has occurred.

print(boolean b) - Print a boolean value.

print(char c) - Print a character.

print(char[ ] s) - Print an array of characters.

print(double d) - Print a double-precision floating-point number.

print(float f) - Print a floating-point number.

print(int i) - Print an integer.

print(long l) - Print a long integer.

print(Object obj) - Print an object.

print(String s) - Print a string.

println( ) - Terminate the current line by writing the System.getProperty(“line.separator”) line separator string.

println(boolean x) - Print a boolean value and then terminate the line.

println(char x) - Print a character and then terminate the line.

println(char[ ] x) - Print an array of characters and then terminate the line.

println(double x) - Print a double and then terminate the line.

println(float x) - Print a floating-point number and then terminate the line.

println(int x) - Print an integer and then terminate the line.

println(long x) - Print a long integer and then terminate the line.

println(Object x) - Print an Object and then terminate the line.

println(String x) - Print a String and then terminate the line.

 

  PrintWriter's methods do not throw I/O Exceptions.  Nor do its constructors.  Instead, you must use checkError( ) after every I/O operation.  i.e.

 

import java.io.*;

 

PrintWriter pw = new PrintWriter( new FileOutputStream( "myoutputfile" ));

pw.print( "some String" );                  

if ( pw.checkError( ) ) {

      // your error handling code goes here

}

pw.flush( );

 

 

  You cannot be sure all your output will actually get written by PrintWriter unless you set the boolean "flush" parameter in its constructors to true.  If you do not elect true you should be sure to execute flush( ) and close( ) statements on your output stream.  In practice, flush( ) and close( ) are recommended all the time.  i.e.

 

import java.io.*;

 

 try {

        PrintWriter pw = new PrintWriter( new FileWriter ("mypoemfile" ));

        pw.println( "Mary had a little lamb" );                       

        pw.println( "Its fleece was white as snow" ); 

        pw.flush( );

        pw.close( );

}

catch (IOException ex) {  }

 

 

  This code uses PrintWriter's println(...) method to create and write a byte file by chaining to a FileOutputStream.

 

import java.io.*;

 

try {    

    PrintWriter pw = new PrintWriter( new FileOutputStream( "mycharfile",  true ));

    pw.println( "Mary had a little lamb." );                           // this line is checked by checkError( )

    if ( pw.checkError( ) ) {

         System.out.println("Error");

    }

    pw.println( "Its fleece was white as snow." );               // this line is unchecked

    if ( pw != null ) {

          pw.close( );                                                  // it won't actually write the records if you don't close it

    }  

}

catch (IOException ex) {  }

 

 

  This snippet uses one of the write(...) methods defined in PrintWriter's parent Writer to print to the console a file known to be 100K or less in size.

 

import java.io.*;

 

 try {

    FileReader fr = new FileReader( "mycharfile" );

    PrintWriter pw = new PrintWriter( System.out, true );

    char c[ ] = new char[100000];

    int x = 0;

    while (( x = fr.read( c ) ) != -1)  {

         pw.write( c, 0, x);

    }

    fr.close( );

    pw.close( );

}

   catch (IOException e) {  }

 

 

  This snippet illustrates adding buffering to a PrintWriter stream by chaining to a BufferedWriter.  It also demonstrates some print(...) methods with different parameters. It produces the following:

 

Dear Sir,

Please send 95.99 dollars and 45 cents handling by (current date in default format)

Be true

 

import java.io.*;

import java.util.*;

 

 try {

 Date d = new Date( );

 PrintWriter pw = new PrintWriter( new BufferedWriter( new FileWriter( "mycharfile" ) ) );

      pw.println( "Dear Sir," );

      pw.print( "Please send " );

      pw.print( 95.99 );

      pw.print( " dollars and ");

      pw.print( 45 );

      pw.print( " cents handling by ");

      pw.println( d );

      pw.print("Be ");

      pw.print( true );

      pw.close( );

}

catch (IOException e) {  }

 

 

  Since System.out is a PrintStream via its grandparent OutputStream, and PrintWriter constructors accept an OutputStream, you can print to the console using PrintWriter methods the same as you can using PrintStream's (identical) methods.  i.e.

 

PrintWriter pw = new PrintWriter( System.out, true );

pw.println( "Hello World!" );

 

 

  Normally buffering is added to PrintWriter streams.  See BufferedWriter class