Java Reference
In-Depth Information
PITFALL:
(continued)
in Display 10.1 with the following:
try
{
PrintWriter outputStream =
new
PrintWriter(
new
FileOutputStream("stuff.txt"));
}
This replacement looks innocent enough, but it makes the variable
outputStream
a
local variable for the
try
block, which would mean that you could not use
output-
Stream
outside of the
try
block. If you make this change and try to compile the
changed program, you will get an error message saying that
outputStream
when used
outside the
try
block is an undefined identifier.
■
PITFALL: Overwriting an Output File
When you connect a stream to a text file for writing to the text file, as illustrated by
what follows, you always produce an empty file:
outputStream =
new
PrintWriter(
new
FileOutputStream("stuff.txt"));
If there is no file named
stuff.txt
, this will create an empty file named
stuff.txt
. If
a file named
stuff.txt
already exists, then this will eliminate that file and create a
new, empty file named
stuff.txt
. So if there is a file named
stuff.txt
before this file
opening, then all the data in that file will be lost. The section “The
File
Class” tells
you how to test to see whether a file already exists so that you can avoid accidentally
overwriting a file. The following subsection shows you how to add data to a text file
without losing the data that is already in the file.
■
Appending to a Text File
When you open a text file for writing in the way we did it in Display 10.1 and a file
with the given name already exists, the old contents are lost. However, sometimes you
instead want to add the program output to the end of the file. This is called
append-
ing to a file
. If you wanted to append program output to the file
stuff.txt
, you
would connect the file to the stream
outputStream
in the following manner:
appending
outputStream =
new
PrintWriter(
new
FileOutputStream("stuff.txt",
true
));