Java Reference
In-Depth Information
Reading and Displaying Text Files
Example 3-3 shows the
FileViewer
class. It combines the use of the
File
class
and I/O streams to read the contents of a text file with GUI techniques to display
those contents.
FileViewer
uses a
java.awt.TextArea
component to display file
contents, as shown in Figure 3-1. Example 3-3 uses graphical user interface tech-
niques that are introduced in Chapter 10,
Graphical User Interfaces
. If you have
not yet read that chapter or do not already have AWT programming experience,
you probably won't understand all the code in the example. That's okay; just con-
centrate on the I/O code, which is the main focus of this chapter.
Figur e 3−1. A FileViewer window
The
FileViewer
constructor concerns itself mainly with the mechanics of setting
up the necessary GUI. There are some interesting uses of the
File
object at the
end of this constructor, however. The heart of this example is the
setFile()
method. This is where the file contents are loaded and displayed. Because the file
contents are to be displayed in a
TextArea
component, the legitimate assumption
is that the file contains characters. Thus, you use a character input stream, a
File-
Reader
, instead of the byte input stream used in the
FileCopy
program of Example
3-2. Once again, use a
finally
clause to ensure that the
FileReader
stream is
properly closed.
The
actionPerformed()
method handles GUI events. If the user clicks on the
Open File button, this method creates a
FileDialog
object to prompt for a new file
to display. Note how the default directory is set before the dialog is displayed and
then retrieved after the user makes a selection. This is possible because the
show()
method actually blocks until the user selects a file and dismisses the dialog.