Lesson 3 | Using PrintWriter |
Objective | Familiarize yourself with how to use PrintWriter. |
Using Java PrintWriters
There are four constructors in the PrintWriter
class.
public PrintWriter(Writer out)
public PrintWriter(Writer out, boolean autoFlush)
public PrintWriter(OutputStream out)
public PrintWriter(OutputStream out,
boolean autoFlush)
The PrintWriter
can either send data to an OutputStream
or to another writer.
If autoFlush
is set to true, the PrintWriter
is flushed every time the println()
method is invoked.
print( ) and println( ) Methods
The main advantages of the
PrintWriter
class are the
- nine-way overloaded
print()
method and
- the 10-way overloaded
println()
method.
println() method overloads
public void println()
public void println(boolean x)
public void println(char x)
public void println(int x)
public void println(long x)
public void println(float x)
public void println(double x)
public void println(char x[])
public void println(String x)
public void println(Object x)
Any Java object, variable, or literal can be printed by passing it to a
print()
or
println()
method.
The
println()
method follows its argument with a platform-dependent line separator such as
\r\n
and then flushes the output if
autoFlush
is enabled. The
print()
method does not. Otherwise these methods are the same.
checkError( ) method
None of the methods of the PrintWriter
class throw IOException
s.
If any exceptions are thrown, they are caught inside the class. You can check to see whether any exceptions have been thrown with checkError()
.
public boolean checkError()
This method returns true if an error has occurred and false if it hasn't. There's no easy way to determine exactly what the error was, though.
Other PrintWriter methods
The PrintWriter
class also contains other PrintWriter methods listed below.
public void flush()
public void close()
public void write(int c)
public void write(char buf[], int offset, int length)
public void write(char buf[])
public void write(String s, int offset, int length)
public void write(String s)
The usual Writer
methods like write()
and flush()
, though it's rare to use them.