next up previous
Next: Reading from a file Up: Unit 09 Previous: Program for reading from

Loop schema for reading from a file

When we read a set of strings from a file, we usually make use of a loop structured as follows:

BufferedReader in = ...
String line = in.readLine();
while (line != null) {
   process line
   line = in.readLine();
}

The loop schema illustrated above represents an iteration on the lines of the file. Indeed, the method readLine() returns the value null if there are not data to read from the file (e.g., when we are at the end of the file). Such a condition is used to verify the termination of the loop.

Example: Method that reads an array of strings from a file.

public static String[] loadArray (String filename) throws IOException {
  // We first read the file to count the number of lines
  FileReader f = new FileReader(filename);
  BufferedReader in = new BufferedReader(f);
  int n = 0;
  String line = in.readLine();
  while (line != null) {
    n++;
    line = in.readLine();
  }
  f.close();

  // Creation of the array
  String[] v = new String[n];

  // Loop to read the strings from the file into the array
  f = new FileReader(filename);
  in = new BufferedReader(f);
  int i = 0;
  line = in.readLine();
  while ((line != null) && (i < n)) {
    v[i] = line;
    line = in.readLine();
    i++;
  }
  f.close();
  return v;
}

This method returns an array of strings corresponding to the lines of text in a file. Note that we read the file twice (using two loops): the first time to count the number of lines of the file, so that we can determine the size of the array; the second time to read the strings that fill up the array. Note also that, to read data twice from the same file, we have to close the file and the re-open it again.


next up previous
Next: Reading from a file Up: Unit 09 Previous: Program for reading from