next up previous
Next: Program for reading from Up: Unit 09 Previous: Loop schema for writing

Reading from a text file

To read strings of text from a file we have to:

  1. open the file for reading by creating an object of the class FileReader and an object of the class BufferedReader associated to the FileReader object we have just created;
  2. read the lines of text from the file by using the readLine() method of the BufferedReader object;
  3. close the file when we are finished reading from it.

The Java statements that realize the three phases described above are:

// 1. opening the file for reading
FileReader f = new FileReader("test.txt");;
BufferedReader in = new BufferedReader(f);

// 2. reading a line of text from the file
String line = in.readLine();

// 3. closing the file
f.close();

Notes:


next up previous
Next: Program for reading from Up: Unit 09 Previous: Loop schema for writing