3.2.3.2 File Input3.2.3.1 Character Streams3.2.3 Text Input3.2.3.3 String Conversion

3.2.3.2 File Input

For reading a text file, we create the fundamental Reader object with the help of the class FileReader:

   public class FileReader extends Reader
   {
      public FileReader(String fileName) 
        throws FileNotFoundException;
      public void close() throws IOException;
      ...
   }

 

The denoted constructor takes a file name (possibly including a path) as an argument and either constructs a new FileReader or throws an exception if the corresponding file could not be found. We may thus open an input file named "in.txt" as follows:  

   // open file
   String name = "in.txt";
   BufferedReader input = null;
   try
   {
     Reader reader = new FileReader(name);
     input = new BufferedReader(reader);
   }
   catch(FileNotFoundException e)
   {
     System.out.println("File " + name + " does not exist.")
     System.exit(-1);
   }

The outcome of this is a BufferedReader object input that we may use for processing the file as follows:

   // process file
   try
   {
     while (true)
     {
       String line = input.readLine();
       if (line == null) break;
       ...
     }
     input.close();
   }
   catch(IOException e)
   {
     System.out.println("IO error: " + e.getMessage());
     System.exit(-1);
   }

 

The close method of BufferedReader invokes the corresponding method of the underlying Reader object (in this case, a FileReader) which signals that the file can be released. Since a process only may have a limited number of files in use, it is good practice to close a file after it has been processed.


© Wolfgang Schreiner; February 3, 2005

3.2.3.2 File Input3.2.3.1 Character Streams3.2.3 Text Input3.2.3.3 String Conversion