Always call method close when finished with it.
I/O exceptions are suppressed by methods of class PrintStream . When you
are finished writing, you can check whether an I/O exception occurred by call-
ing function ps.checkError() ; it returns true iff there was an I/O error.
Appending instead of overwriting
It is possible to append to a file instead of overwriting it. Figure 5.8 contains
a method, getAppender , which obtains the name of a file to append to from the
user and returns a PrintStream . Writing to this PrintStream will append to,
rather than overwrite, the file.
Here are the differences between getAppender and getWriter of Fig. 5.6:
Get the func-
tion in Fig. 5.8
from a footnote
on lesson page
The title of the dialog window is changed to reflect the new task.
Instead of creating a PrintStream using new FileOutputStream(f) ,
new FileOutputStream(f.getPath(), true )
is used. The first argument is not f itself but a String that contains its
name (i.e. the complete, absolute path to the file). The second argument,
true , indicates that the file should be appended to. A second argument of
false would cause the file to be overwritten.
In the dialog window that appears, the user cannot type a file name; they can
only select one to append to.
Exercises with files
In the following exercises, it is best to start with the appropriate class from Fig.
5.5, 5.6, or 5.7 and modify it.
E1. In the Interactions pane of DrJava, import java.io.* . Next, type the first
three statements of method readAndProcess of Fig. 5.5, which will read in one
line from the keyboard. Notice how DrJava gives you a place to type (in the
Interactions pane). Type in something. Now see what the value of variable line
is. You need DrJava from August 2003 or later.
E2. In DrJava, create a new class and place method readAndProcess of Fig. 5.5
in it. Compile the class and then test it by calling readAndProcess from the
Interactions pane. You need DrJava from August 2003 or later.
E3. Write (and test) a procedure that (1) obtains a (text) file from the user, (2)
reads its lines until a line with "END" on it is read (or until there are no more
lines to read), and (3) prints the number of lines read.
E4. Assume that each line of a file contains an integer, possibly surrounded by
blanks. Write (and test) a procedure that obtains the name of the file from the
user, reads the file, and prints the sum of the integers.