O'Reilly logo

Java Examples in a Nutshell, 3rd Edition by David Flanagan

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 techniques that are introduced in Chapter 11. 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 concentrate on the I/O code, which is the main focus of this chapter.

A FileViewer window

Figure 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, we use a character input stream, a FileReader, 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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required