Java Reference
In-Depth Information
The next part reads the file and prints the line lengths, using a loop that
processes one line of a file at a time. There is a difference between reading a file
and reading the keyboard. If there are no more lines to read in a file, function
br.readLine()
returns
null
. But there is no concept of the end of the keyboard,
so the method that reads a line waits until the reader has typed another line.
Note the last statement of the method body,
br.close();
which closes the file, making it impossible to read from it anymore with variable
br
. In this program, it is not necessary to include this statement because the pro-
gram will terminate right after this statement anyway. However, in general, it is
a good practice to include it, just in case another part of the program attempts to
open and use the same file.
import
java.io.*;
import
javax.swing.*;
public class
WriteExample {
/**
Get an output file name from the user and print two lines on it
*/
public static void
main(String[] args)
throws
IOException {
PrintStream ps= getWriter();
if
(ps ==
null
) {
System.out.println(" User canceled. Nothing was written.");
return
;
}
//
Print two lines on the file
ps.println(" This is the first line.");
ps.println(" This is the second line.");
System.out.println( "File has been written." );
ps.close();
}
/**
Obtain a file name from the user, using a
JFileChooser
, and return
a
PrintStream
that is linked to it. Return
null
if the user cancels
*/
public static
PrintStream getWriter()
throws
IOException {
JFileChooser jd= new JFileChooser();
jd.setDialogTitle("Choose output file");
jd.showSaveDialog(
null
);
File f= jd.getSelectedFile();
if
(f ==
null
) {
return null
; }
return new
PrintStream(
new
FileOutputStream(f));
}
}
Figure 5.7:
Print two lines on a file chosen by the user
Search WWH ::
Custom Search