3.2.2.2 Standard Input3.2.2.1 Standard Output3.2.2 Standard Input and Output3.2.3 Text Input

3.2.2.2 Standard Input

The variable System.in denotes the  standard input stream. It is of type InputStream which provides (among others) the following core method:

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

 

This method reads up to len bytes into the array b at b[off...off+len-1]. The actual number of bytes read (which may be less than len) is returned as the function result. The method blocks until bytes are available or the end of file is detected or an error occurs. If the end of file is detected, the function returns -1. If an error occurs, an IOException is thrown.  

With this method, we can therefore read a number of bytes as follows:

  final int N = 100;
  byte b[] = new byte[N];
  try
  {
    int n = System.in.read(b, 0, N);
    if (n == -1) return;             // end of file
    ...                              // process b[0..n-1]
  }
  catch(IOException e)
  {
    System.out.println("IO error: " + e.getMessage());
    System.exit(-1);
  }

However, the outcome of the read method is an array of byte, not a high-level datatype. This method is therefore typically not used in application programs. The actual role of System.in is explained in the next section.


© Wolfgang Schreiner; February 3, 2005

3.2.2.2 Standard Input3.2.2.1 Standard Output3.2.2 Standard Input and Output3.2.3 Text Input