Java Reference
In-Depth Information
9. while(currentState != null) {
10. System.out.println(“State: “ + currentState);
11. currentState = in.readLine();
12. }
13. }catch(IOException e) {
14. e.printStackTrace();
15. }
16. }
17. }
Here is what the States program does:
1. A new FileReader is instantiated on line 6. If the file states.txt is not found or can-
not be read from, a FileNotFoundException is thrown.
2. A BufferedReader is chained to the FileReader to buffer the data.
3. Line 8 reads in the first line of text from the file.
4. On line 9, if the previous line of text read from the file is not null , we print it to the
console and read in the next line of the file on line 11.
5. The while loop continues line by line until the end of the file is reached, at which point
the readLine method returns null .
The output of the States program is
State: New York
State: Alabama
State: South Dakota
State: Nevada
Figure 4.7 shows the BufferedReader chained to the FileReader . A BufferedReader
cannot exist on its own. It is a high-level stream so it must be attached to an existing
stream.
FIGURE 4.7 A BufferedReader is chained to a FileReader .
BufferedReader
“New York”
FileReader
1011010
“states.txt”
Search WWH ::




Custom Search