Java Reference
In-Depth Information
Reading a file
Reading a file is more work than reading the keyboard because the file to read
must be chosen by the user. For this purpose, we suggest displaying a dialog
window in which the user can navigate to a folder and choose the desired file.
Such a task can be accomplished using an instance of class JFileChooser in
package javax.swing .
Figure 5.6 contains a program, which obtains a file from the user and then
reads the lines of the file and prints their lengths. We discuss it in two parts.
5-7.5, 6-7.6
Get the pro-
gram in Fig.
5.6 from a
footnote on les-
son page 5-7.
Obtaining a file from the user
Method getReader creates the BufferedReader that is attached to a file
chosen by the user. Whenever you have to write a program that will read from a
file selected by the user, use this method.
First, note that the header of function getReader contains a throws clause
because it may throw an IO exception.
Now examine the method body. Here are the first four statements:
JFileChooser jd= new JFileChooser();
jd.setDialogTitle("Choose input file");
jd.showOpenDialog( null );
File f= jd.getSelectedFile();
The first statement creates an instance of JFileChooser and stores it in
local variable jd . Attached to this instance is a dialog window on the user's mon-
itor, which is not yet visible. The second statement set the title of the window so
that the user knows what the dialog box is for. The third statement makes the dia-
log window visible and then waits until the user has either selected a file name
or clicked the cancel button in the dialog window. The fourth statement obtains
an object of class File that represents the file the user chose — f will be null if
the user clicked the cancel button.
This is the standard way to obtain a file from the user.
Next, if f is null , the method returns the value null , as indicated in the
specification of the method. If f is not null , this statement is executed:
return new BufferedReader( new FileReader(f));
It creates an instance of class FileReader that is attached to file f , creates an
instance of BufferedReader that is attached to the instance of FileReader , and
returns the BufferedReader .
Obtain this program from ProgramLive and run it so that you can see what
the dialog window looks like.
Reading and processing the file
The first statement in method main calls method getReader to obtain a
BufferedReader that is linked to the user's file.
Search WWH ::

Custom Search