Reading Console Input in Java

Waqas Anwar
06 April 2008
10100 Views

Reading console input in simple java console applications is a very straight forward process. Java provides developers two predefined streams in the java.lang.System class to read and write data to and from standard input and output devices. System.out is a standard output stream which is Console by default and System.in is predefined input stream which is Keyboard by default. To read user input in a console window we connect system.in with other stream classes available in java.io package.

Following code example shows you how to read user input in console window in java.

import java.io.*;

public class ConsoleInput
{
      public static void main(String[] args) throws Exception
      {
            System.out.println("Enter Your Text: " );   
            InputStreamReader r = new InputStreamReader(System.in);
            BufferedReader br = new BufferedReader(r); 
            String s = br.readLine(); 
            System.out.println(s);     
      }
}