Java Input/Output  « Prev 

Reading from Standard Input in Java

This program keeps reading until the user presses Enter (which the program detects by looking for a new line character).

import java.io.*;

class FirstEcho {
   public static void main(String[ ] args) {
      try {
          char c;
          StringBuffer sb = new StringBuffer();
          while ((c = (char)System.in.read()) != '\n')
             sb.append( c );
          System.out.println( sb );
      } catch (IOException e) {
      }
   }
}

This stand-alone program must cast the result of read() to a char. The result of read() is actually an int representing the ASCII character read (in other words, it is in the range of 0 to 255). However, when read() reaches the end of the data, it returns the value -1. You can make this occur when entering data from the keyboard by typing Ctrl-Z. Otherwise, this will occur when reading from a file when you have reached the end.
The read() method might also throw an IOException if it encountered a problem when attempting to perform the read. So, we set up the read() call within a try block and catch any IOExceptions that occur.