Java – How to read input from the console

In Java, there are three ways to read input from a console :

  1. System.console (JDK 1.6)
  2. Scanner (JDK 1.5)
  3. BufferedReader + InputStreamReader (Classic)

1. System.console

Since JDK 1.6, the developer starts to switch to the more simple and powerful java.io.Console class.

JavaConsole.java

package com.mkyong.io;

import java.io.Console;

public class JavaConsole {

    public static void main(String[] args) {

        Console console = System.console();

        String input = "";
        while (!"q".equalsIgnoreCase(input)) {

            System.out.print("Enter something (q to quite): ");

            input = console.readLine();
            System.out.println("input : " + input);
        }

        System.out.println("bye bye!");
    }

}

The System.console() will return null in IDE, running the class in console or terminal manually.



~/projects/target/classes$ java com.mkyong.io.JavaConsole

Enter something (q to quite): hello 123
input : hello 123
Enter something (q to quite): hello Java
input : hello Java
Enter something (q to quite): mkyong
input : mkyong
Enter something (q to quite): q
input : q
bye bye!

P.S More Java System.console() examples.

2. Scanner

Before JDK 1.6, this is the Scanner way to read input from the console.

JavaScanner.java

package com.mkyong.io;

import java.util.Scanner;

public class JavaScanner {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        String input = "";
        while (!"q".equalsIgnoreCase(input)) {

            System.out.print("Enter something (q to quite): ");

            input = scanner.nextLine();
            System.out.println("input : " + input);
        }

        System.out.println("bye bye!");
    }

}

Enter something (q to quite): hello mkyong
input : hello mkyong
Enter something (q to quite): jdk 1.5
input : jdk 1.5
Enter something (q to quite): exit
input : exit
Enter something (q to quite): q
input : q
bye bye!

P.S More Java Scanner examples examples.

3. BufferedReader + InputStreamReader

In the old days, JDK 1.1, we use BufferedReader + InputStreamReader to read input from the console.

JavaBufferedReaderClassic.java

package com.mkyong.io;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class JavaBufferedReaderClassic {

    public static void main(String[] args) {

        BufferedReader br = null;

        try {

            br = new BufferedReader(new InputStreamReader(System.in));

            String input = "";
            while (!"q".equalsIgnoreCase(input)) {

                System.out.print("Enter something (q to quite): ");

                input = br.readLine();
                System.out.println("input : " + input);
            }

            System.out.println("bye bye!");

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

}

JDK 1.7 try-with-resources

JavaBufferedReader.java

package com.mkyong.io;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class JavaBufferedReader {

    public static void main(String[] args) {

        // jdk 1.7
        try (BufferedReader br = new BufferedReader(new InputStreamReader(System.in))) {

            String input = "";
            while (!"q".equalsIgnoreCase(input)) {

                System.out.print("Enter something (q to quite): ");

                input = br.readLine();
                System.out.println("input : " + input);
            }

            System.out.println("bye bye!");

        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}

References

35 comments on “Java – How to read input from the console

  1. Sir, Can u please update this blog with the latest functionality if it is available in newer versions of java?
    This article is too old so m concerned if I’m not learning updated and latest way to solve the issue.

    Reply
  2. System.console() also does not work in competitive programming environments, such as open.Kattis.com

    Reply
  3. hello why we use exception in BufferReader

    Reply
  4. Hello MKYong & everyone, I was learning java2 jdk1.3 in 2002-2003 then suddenly I had to left it bcz of change of field now again after an interval of 12-13years I m again interested in learning Java, so I found your article helpful as you have given all three examples of jdk1.3,1.5&1.6 that’s very good I appreciate your work, thanks regards from me(Mohsin)

    Reply
  5. very helpful Thank you…!
    There is another method for reading console
    DataInputStream dis= new DataInputStream(System.in); which defined in java.io. Like BufferedReader it also uses Integr.parseInt(dis.readLine( )); to read from console

    Reply
    1. Thanks for you input. For JDK >= 1.6, better use the Console class.

      Reply
  6. which is the best method to read input from the above mentioned methods?
    and please tell me use of each method?
    because i’m confused.

    Reply
    1. Article is updated, for JDK >= 1.6, better use the java.io.Console class.

      Reply
  7. Is it possible to getting console error in String..pls guide me or mail me…Advanced Thanks.

    Reply
  8. This was very helpful for my facial reconstruction simulation project…
    thank you..!!

    Reply
    1. You are so helpful. May God bless you.

      Can you give me a hand in using JDPAPI to protect some credentials like, password, username network address.

      Reply
  9. Is it legal not to call close method of BufferedReader class while reading from console?

    Reply
  10. Since java 6 there is another shorter way (like in c#) to read/write from the system console :
    System.console().readLine();

    or just instatiate a Console reference (java.io.Console) and assign a it to the system’s console :

    Console c = System.console();
    c.readLine();

    Reply
    1. Also the Console way is thread safe the other two methods are not just to point out another difference. If you look in the source code of the java.io.Console class you will see that readLine uses locks to prevent concurrent read/write access.

      Personally i prefer the console way for simple and the scanner way, when you need to tokenize the input.

      Reply
    2. Thanks, article is updated, the JDK 1.6 System.console() is a better choice.

      Reply
  11. Scanner IMHO is great, since it seems to me more concise, however if you enter dot’s and/or comma’s through numeric pad section of your keyboard, – be surprised to find out that you are not a citizen of Great Britain: Scanner mixes up numeric locales (I am from Russia just in case)

    Reply
  12. Wow you are amazing, each day i randomly search in google and i find solutions in this page.
    thank you again!

    Reply
  13. I want to read spaces from input and the scanner throws an exception while doing so. I want to use every ‘other’ whitespace character as delimiter except space. Any help with scanner? Or shall I continue to use BufferedReader?
    I have very small inputs to fetch as in “Hello World” or “I am new”

    Reply
  14. But scanner will not be a good practice unless the input is very small. ( less than 50KB of data is to be read )

    Reply
  15. This example is not a useful solution for me.
    I want to accept current/default number (by pressing enter) or change number by
    input number and press enter.
    Further if I happen to input a character java crashes, very bad !

    I haven’t found a solution yet,
    /Jarl

    Reply
  16. What about the System.Io.Console class new to Java 6? It seems even simpler, but I heard it can produce glitches depending on whether console on the particular JVM is started automatically or not.

    Reply
    1. ya , Scanner provide many new functionality, may be i’m an old guy, used to BufferedReader already haha

      Reply

Leave a Comment

Your email address will not be published. Required fields are marked *