Java Reference
In-Depth Information
Writing and appending to a file
Figure 5.7 contains a complete program that obtains a file name from the user,
using a JFileChooser , and prints two lines on it. This has the same structure as
the one in Fig. 5.6, which reads a file, and it will need less discussion.
page 5-8
Obtaining a file name from the user
Method getWriter creates an instance of class PrintStream that is
attached to a file chosen by the user. Whenever you have to write a program that
will write a file chosen by the user, use this method.
The method stores a new JFileChooser in variable jd and gives it an
appropriate title. Then it calls method jd.showSaveDialog (instead of
OpenDialog ). This method opens a dialog window in which the user can navi-
gate to a directory and type in a file name. In the dialog window, file names are
grayed; the user cannot select an existing file to write. It is possible to set a
switch in the instance js that allows the user to select an existing file to over-
write, but this can be dangerous.
As in the case of method getReader , a File f is created once the user has
selected a file. If f is null , that means the user canceled the selection, and the
function returns null . Otherwise, it creates and returns an instance of class
PrintStream that is attached to the user's file.
Get the pro-
gram in Fig.
5.7 from a
footnote on les-
son page 5-8.
Writing the output file
Instance ps in method main has methods print(e) and println(e) .
Argument e can be any expression. Its value is converted to a character repre-
sentation and appended to the file, with a line separator in the case of println .
In the example of Fig. 5.7, method main simply writes two lines to the file.
It then prints a message indicating that the file was written and closes the file.
/** Obtain a file name from the user, using a JFileChooser , and return a PrintStream that
is linked to it and that appends to the file instead of overwriting it.
Return null if the user cancels */
public static PrintStream getAppender() throws IOException {
JFileChooser jd= new JFileChooser();
jd.setDialogTitle("Choose file to append to");
jd.showOpenDialog( null );
File f= jd.getSelectedFile();
if (f == null ) {
return null ;
return new PrintStream( new FileOutputStream(f.getPath(), true ));
Figure 5.8: Obtaining a PrintStream that appends to a file
Search WWH ::

Custom Search