Java Reference
In-Depth Information
TIP:
toString
Helps with Text File Output
In Chapter 4 , we noted that if a class has a suitable
toString()
method and
anObject
is an object of that class, then
anObject
can be used as an argument to
System.out.println
, which will produce sensible output.
1
The same thing applies
to the methods
println
and
print
of the class
PrintWriter
. Both
println
and
print
of the class
PrintWriter
can take any object as an argument and will produce
reasonable output so long as the object has a sensible
toString()
method.
■
Opening a Text File for Appending
To create an object of the class
PrintWriter
and connect it to a text file for appending to
the end of the text already in the file, proceed as follows.
SYNTAX
Output_Stream_Name
=
new
PrintWriter(
new
FileOutputStream(
File_Name, True_Boolean_Expression
));
EXAMPLE
PrintWriter outputStream;
outputStream =
new
PrintWriter(
new
FileOutputStream("stuff.txt",
true
));
After this statement, you can use the methods
println
and
print
to write to the file, and
the new text will be written after the old text in the file.
(If you want to create a stream using an object of the class
File
, you can use a
File
object in place of the
File_Name
. The
File
class is discussed later in the section entitled
“The
File
Class.”)
When used in this way, the
FileOutputStream
constructor, and so the
PrintWriter
constructor invocation, can throw a
FileNotFoundException
, which is a kind of
IOException
.
Self-Test Exercises
3. What kind of exception might be thrown by the following, and what would it
indicate if this exception is thrown?
PrintWriter outputStream =
new
PrintWriter(
new
FileOutputStream("stuff.txt"));
1
There is a more detailed discussion of this in Chapter 8, but you need not read Chapter 8 to use
this fact.