Java Reference
In-Depth Information
If the file
stuff.txt
does not already exist, Java will create an empty file of that name
and append the output to the end of this empty file. So if there is no file named
stuff.txt
, the effect of opening the file is the same as in Display 10.1. However, if the
file
stuff.txt
already exists, then the old contents will remain, and the program's out-
put will be placed after the old contents of the file.
When appending to a text file in this way, you would still use the same
try
and
catch
blocks as in Display 10.1.
That second argument of
true
deserves a bit of explanation. Why did the designers
use
true
to signal appending? Why not something like the string
"append"
? The reason
is that this version of the constructor for the class
FileOutputStream
was designed to
also allow you to use a Boolean variable (or expression) to decide whether you append to
an existing file or create a new file. For example, the following might be used:
System.out.println(
"Enter A for append or N for a new file:");
char
answer;
<
Use your favorite way to read a single character into the variable
answer
.
>
boolean
append = (answer == 'A' || answer == 'a');
outputStream =
new
PrintWriter(
new
FileOutputStream("stuff.txt", append));
From this point on, your program writes to the file in exactly the same way that the pro-
gram in Display 10.1 does. If the user answered with upper- or lowercase A, then any
input will be added after the old file contents. If the user answered with upper- or lower-
case N (or with anything other than an A), then any old contents of the file are lost.
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
and that 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 reason-
able output so long as the object has a sensible
toString()
method.
■
1
1
There is a more detailed discussion of this in Chapter 8, but you need not read Chapter 8 to use this
fact.