-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path71FileRead.java
40 lines (34 loc) · 981 Bytes
/
71FileRead.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class FileReaderExample
{
public static void main(String args[])
{
// The name of the file to open
String fileName = "temp.txt";
// This will reference one line at a time
String line = null;
try
{
// FileReader reads text files in the default encoding
FileReader fileReader = new FileReader(fileName);
// Always wrap FileReader in BufferedReader
BufferedReader bufferedReader = new BufferedReader(fileReader);
int lineNumber = 1;
while((line = bufferedReader.readLine()) != null)
{
System.out.println(lineNumber + ": " + line);
lineNumber++;
}
// Always close files
bufferedReader.close();
}
catch(IOException ex)
{
System.out.println("Error reading file '" + fileName + "'");
// Or we could just do this:
// ex.printStackTrace();
}
}
}