3.2.3.1 Character Streams3.2.3 Text Input3.2.3 Text Input3.2.3.2 File Input

3.2.3.1 Character Streams

The class InputStreamReader serves as a bridge between byte streams and character streams:

   public class InputStreamReader extends Reader
   {
      public InputStreamReader(InputStream in);
      ...
   }

This class provides a constructor which takes an InputStream object in and creates a character stream which is connected to in. We can for instance create a character stream connected to the standard input stream as

   Reader reader = new InputStreamReader(System.in);

Class InputStreamReader itself does not provide many interesting methods; its main functionality is inherited from class Reader. We therefore declare the variable reader as Reader and forget that it actually is a InputStreamReader object. Class Reader provides the following core method:

 

   public abstract class Reader
   {
     abstract public int read(char[] b, int off, int len) 
       throws IOException; 
     ...
   }

The functionality of read is the same as of the corresponding method in class InputStream with the only difference that an array of characters is filled rather than an array of bytes. However, this is not yet sufficient for our purposes. We therefore map the character stream to a stream of type BufferedReader:

 

   public class BufferedReader extends Reader
   {
      public BufferedReader(Reader in);
      public String readLine() throws IOException;
      public void close() throws IOException;
      ...
   }

We can thus create a buffered reader stream as follows:

   BufferedReader stdin = new BufferedReader(reader);

The class BufferedReader provides a method readLine() which reads a complete input line and returns it as a String object. the end of the stream has been reached, the method returns null.

We can therefore read a string as follows:

  try
  {
    String s = stdin.readLine();
    if (s == null) return;       // end of file
    ...                          // process s
  }
  catch(IOException e)
  {
    System.out.println("IO error: " + e.getMessage());
    System.exit(-1);
  }

Thus we have gained the possibility of reading a string from standard input. How to read a string from a text file will be explained in the next section.


© Wolfgang Schreiner; February 3, 2005

3.2.3.1 Character Streams3.2.3 Text Input3.2.3 Text Input3.2.3.2 File Input