Java Reference
In-Depth Information
Checking for the End of a Text File with BufferedReader
The method readLine of the class BufferedReader returns null when it tries to read
beyond the end of a text file. The method read of the class BufferedReader returns -1
when it tries to read beyond the end of a text file.
Display 10.9
Checking for the End of a Text File with BufferedReader (part 1 of 2)
1 import java.io.BufferedReader;
2 import java.io.FileReader;
3 import java.io.PrintWriter;
4 import java.io.FileOutputStream;
5 import java.io.FileNotFoundException;
6 import java.io.IOException;
7 /**
8 Makes numbered.txt the same as original.txt, but with each line numbered.
9 */
10 public class TextEOFDemo
11 {
12 public static void main(String[] args)
13 {
14 try
15 {
16 BufferedReader inputStream =
17 new BufferedReader( new FileReader("original.txt"));
18 PrintWriter outputStream =
19
new PrintWriter( new FileOutputStream("numbered.txt"));
20 int count = 0;
21 String line = inputStream.readLine();
22 while (line != null )
23 {
24 count++;
25 outputStream.println(count + " " + line);
26 line = inputStream.readLine();
27 }
28 inputStream.close();
29 outputStream.close();
30 }
31 catch (FileNotFoundException e)
32 {
33 System.out.println("Problem opening files.");
34 }
35 catch (IOException e)
36 {
37 System.out.println("Error reading from original.txt.");
38 }
39 }
40 }
Search WWH ::




Custom Search