Print Writers – Java I/O: Part I

Print Writers

The capabilities of the OutputStreamWriter and the InputStreamReader classes are limited, as they primarily write and read characters.

In order to write a text representation of Java primitive values and objects, a Print-Writer should be chained to either a writer, or a byte output stream, or accept a String file name, using one of the following constructors:

Click here to view code image

PrintWriter(Writer out)
PrintWriter(Writer out, boolean autoFlush)
PrintWriter(OutputStream out)
PrintWriter(OutputStream out, boolean autoFlush)
PrintWriter(String fileName) throws FileNotFoundException
PrintWriter(String fileName, Charset charset)
            throws FileNotFoundException
PrintWriter(String fileName, String charsetName)
            throws FileNotFoundException, UnsupportedEncodingException

The boolean autoFlush argument specifies whether the PrintWriter should do automatic line flushing.

When the underlying writer is specified, the character encoding supplied by the underlying writer is used. However, an OutputStream has no notion of any character encoding, so the necessary intermediate OutputStreamWriter is automatically created, which will convert characters into bytes, using the default character encoding.

boolean checkError()
protected void clearError()

The first method flushes the output stream if it’s not closed and checks its error state.

The second method clears the error state of this output stream.

Writing Text Representation of Primitive Values and Objects

In addition to overriding the write() methods from its super class Writer, the Print-Writer class provides methods for writing text representation of Java primitive values and of objects (see Table 20.6). The println() methods write the text representation of their argument to the underlying stream, and then append a line separator. The println() methods use the correct platform-dependent line separator. For example, on Unix-based platforms the line separator is ‘\n’ (newline), while on Windows-based platforms it is “\r\n” (carriage return + newline) and on Mac-based platforms it is ‘\r’ (carriage return).

Table 20.6 Print Methods of the PrintWriter Class

The print() methodsThe println() methods
_
print(boolean b)
print(char c)
print(int i)
print(long l)
print(float f)
print(double d)
print(char[] s)
print(String s)
print(Object obj)

println()
println(boolean b)
println(char c)
println(int i)
println(long l)
println(float f)
println(double d)
println(char[] ca)
println(String str)
println(Object obj)

The print methods create a text representation of an object by calling the toString() method on the object. The print methods do not throw any IOException. Instead, the checkError() method of the PrintWriter class must be called to check for errors.