Friday, 17 July 2015

How to read input from console in Java?

Here I am giving three ways to read input from console -

  • First way uses the InputStreamReader wrapped in a BufferedReader.
  • Second way uses the Scanner class from Java 5.
  • Third way uses the System.console which was introduced in Java 6.

In order to make it clear I am also providing a short description of the classes or fields used which is mainly taken from the java doc.

  1. System.in - in is a field in a System class. in is the "standard" input stream. This stream is already open and ready to supply input data. Typically this stream corresponds to keyboard input or another input source specified by the host environment or user.
  2. InputStreamReader - An InputStreamReader is a bridge from byte streams to character streams: It reads bytes and decodes them into characters using a specified charset. The charset that it uses may be specified by name or may be given explicitly, or the platform's default charset may be accepted. For top efficiency, consider wrapping an InputStreamReader within a BufferedReader.
  3. BufferedReader - Reads text from a character-input stream, buffering characters so as to provide for the efficient reading of characters, arrays, and lines.
  4. Scanner - A simple text scanner which can parse primitive types and strings using regular expressions. A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace. nextLine() method of the Scanner class advances this scanner past the current line and returns the input that was skipped.
  5. console method - console method in System class whose general form is -
    public static Console console()
    Returns the unique Console object associated with the current Java virtual machine, if any.

A word of caution, if running the code from eclipse System.Console will throw null pointer exception.

Please follow this discussion to know more about this exception -
http://stackoverflow.com/questions/104254/java-io-console-support-in-eclipse-ide
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;

public class ReadFromConsole {

    public static void main(String[] args) {
        // Using InputStreamReader
        System.out.println("Please enter user name : ");            
        BufferedReader bufferRead = new BufferedReader(new InputStreamReader(System.in));
        String s;
        try {            
            s = bufferRead.readLine();
            System.out.println(s);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
        // Using Scanner 
        System.out.println("Please enter user name : ");
        Scanner scanIn = new Scanner(System.in);
        String scanInput = scanIn.nextLine();
        System.out.println(scanInput);
        scanIn.close();  
        
        //Using System.console()
        String username = System.console().readLine("Please enter user name : ");   
        System.out.println("You entered : " + username); 
    }
}

As already mentioned, if used from eclipse the console method will give the following error.
Console.readLine will give error if used from eclipse.

Exception in thread "main" java.lang.NullPointerException
 at org.netjs.examples.ReadFromConsole.main(ReadFromConsole.java:31)

That's all for this topic How to read input from console. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Reading file in Java using BufferedReader
  2. How to read file from the last line in Java
  3. How to find last modified date of a file in Java
  4. Zipping files in Java
  5. Reading delimited file in Java using Scanner

You may also like -

>>>Go to Java Programs page

No comments:

Post a Comment