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 ...

Get Java Examples in a Nutshell, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.