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

                requires the filename argument to specify an existing file. The FileNotFoundException is a checked ex- ception, so unless you want to use a throws clause, you must put the FileReader constructor call in a try block, and the corresponding catch block’s parameter must match the FileNotFoundException.
Toopenafilefortextinput,allyouneedtodoisusenew Scanner(new FileReader(<filename>))
as shown above. You don’t have to know why it is the way it is. But if you’re curious, here’s an explanation:
None of the various Scanner constructors accepts a filename argument like the PrintWriter construc- 3
tor in Figure 15.2 does. So if you want to use Scanner, you must use it in combination with another class that does accept a filename argument and also matches the parameter type in one of the available Scanner constructors. One of Scanner constructors has a Readable parameter type. Since the FileReader class implements the Readable interface, you can instantiate a FileReader object and supply it as an argument in this Scanner constructor.
The FileReader object buffers input from the file and transforms the file’s bytes into characters. The Scanner object converts the stream of characters into strings and numbers. Here’s what the text input process looks like:4
File
string stream of characters stream of bytes or
number
Example Program Apago PDF Enhancer
Let’s now see how text-file input works in the context of a complete program. Suppose you have a text file named markAntony.txt that contains the quotation from Shakespeare’s play Julius Caesar shown in Figure 15.4a. Also, suppose you have a text file named randomNumbers.txt that contains the list of random numbers shown Figure 15.4b.
Figure 15.4a Contents of markAntony.txt text file
Figure 15.4b Contents of randomNumbers.txt text file
3 The Scanner constructor with a String parameter reads a plain old string, not a file.
4 Optionally, you can speed up execution by inserting a BufferedReader object between the Scanner and FileReader objects.
15.4 Text-File Input 609
  FileReader
 Buffer
      Scanner
  Friends, Romans, countrymen, Lend me your ears;
I come to bury Caesar,
not to praise him.
 0.9709900750891582 0.3874009922012617 0.1262329780823327 0.7782696919307651 0.15480236215303655 0.9756100238518657
 











































































   641   642   643   644   645