Java Reference
In-Depth Information
PITFALL: (continued)
“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, “Appending to a
Text File,” 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 appending
to a file . If you want to append program output to the file stuff.txt , connect the file
to the stream outputStream in the following manner:
appending
outputStream =
new PrintWriter( new FileOutputStream("stuff.txt", true ));
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
output 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 such as 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
program in Display 10.1 does. If the user answers with upper- or lowercase A, then
any input will be added after the old file contents. If the user answers with upper- or
lowercase N (or with anything other than an A), then any old contents of the file are lost.
 
Search WWH ::




Custom Search