Page 642 - Introduction to Programming with Java: A Problem Solving Approach
P. 642

                608 Chapter 15 Files
Figure 15.3’s explicit FileWriter performs the same basic streaming activity that Figure 15.2’s implicit
FileWriter performs. In either case, here’s what the text output process looks like:2 File
string
stream of characters stream of bytes
There’s one additional item worth mentioning in Figure 15.3. Notice the fileOut assignment, repeated here for your convenience:
fileOut = new PrintWriter(new FileWriter(stdIn.nextLine(), true));
anonymous object
Thenew FileWritercode,embeddedinPrintWriter’sconstructorcall,isanexampleofananony- mous object. Anonymous objects are very common when working with files because file constructors often use other file objects as arguments. In those cases, there’s no need to save the newly instantiated argument file in a separate variable. Just use it anonymously.
15.4 Text-File Input
Suppose you have a large amounAt opf ianpugt doata tPhatDyoFu neeEdntohuseamnorce tehanronce. Instead of entering it directly from the keyboard repeatedly, it’s more efficient and more reliable to enter it into a file just once. You can create a Java-readable text file with almost any text editor or word processor, provided you save it as “Plain Text.” Then read the data from the file each time you need it. In this section, we show you how to read input from a text file.
Opening a Text File for Input
It’s possible to open a file for input using an instance of the FileReader class with a filename argument. That enables you to read in one character at a time. Sometimes that’s what you want to do. But usually you would rather read a whole line, a whole word, or some type of number. Scanner has methods that per- form these other operations. So, to open a text file for string input, we recommend that you instantiate the FileReader and Scanner classes together in a single statement, as shown below:
Scanner <reference-variable>;
...
<reference-variable> = new Scanner(new FileReader(<filename>));
If the file specified by the FileReader constructor’s filename argument is invalid, the JVM throws a FileNotFoundException. That should sound familiar—we said the same thing about the PrintWriter constructor for text-file output. But there is an important difference. The PrintWriter constructor allows the filename argument to specify a non-existent file. The FileReader constructor
2 Optionally, you can speed up execution by inserting a BufferedWriter object between the PrintWriter and FileWriter objects.
  FileWriter
 Buffer
    PrintWriter
           













































































   640   641   642   643   644