How to read input from console – Java

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

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

1. BufferedReader + InputStreamReader

For experienced Java developers, you will miss this classic way to read a system input.

ReadConsole.java

package com.mkyong;

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

public class ReadConsole {

    public static void main(String[] args) {

        BufferedReader br = null;

        try {

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

            while (true) {

                System.out.print("Enter something : ");
                String input = br.readLine();

                if ("q".equals(input)) {
                    System.out.println("Exit!");
                    System.exit(0);
                }

                System.out.println("input : " + input);
                System.out.println("-----------\n");
            }

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

    }

}

Output

Enter something : old and classic
input : old and classic
-----------

Enter something : q
Exit!

2. Scanner

In JDK 1.5, the developer starts to use java.util.Scanner to read system input.

ReadConsole2.java

package com.mkyong;

public class ReadConsole2 {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        while (true) {

            System.out.print("Enter something : ");
            String input = scanner.nextLine();

            if ("q".equals(input)) {
                System.out.println("Exit!");
                break;
            }

            System.out.println("input : " + input);
            System.out.println("-----------\n");
        }

        scanner.close();

    }

}

Output

Enter something : hello jdk 1.5
input : hello jdk 1.5
-----------

Enter something : scanner example
input : scanner example
-----------

Enter something : q
Exit!

3. System.console

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

ReadConsole3.java

package com.mkyong;

public class ReadConsole3 {

    public static void main(String[] args) {

        while (true) {

            System.out.print("Enter something : ");
            String input = System.console().readLine();

            if ("q".equals(input)) {
                System.out.println("Exit!");
                System.exit(0);
            }

            System.out.println("input : " + input);
            System.out.println("-----------\n");
        }

    }

}

Output

Enter something : hello jdk 1.6
input : hello jdk 1.6
-----------

Enter something : console example
input : cosole example
-----------

Enter something : q
Exit!
Note
This System.console() is usable only outside IDE, a bit hard for testing.

References

  1. JavaDoc – java.io.Console
  2. JavaDoc – java.util.Scanner
  3. why do we use console class

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.

Comments

avatar
24 Comment threads
11 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
27 Comment authors
Ashish RatanRichardsanthoshMohsinmkyong Recent comment authors
newest oldest most voted
Arun
Guest
Arun

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

mkyong
Guest
mkyong

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

Arjun K
Guest
Arjun K
Férnas
Guest
Férnas

Useful for me, thanks!

Ashish Ratan
Guest
Ashish Ratan

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.

Richard
Guest
Richard

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

santhosh
Guest
santhosh

hello why we use exception in BufferReader

Mohsin
Guest
Mohsin

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)

vinay kumar
Guest
vinay kumar

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.

mkyong
Guest
mkyong

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

Ashok
Guest
Ashok

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

mayantha
Guest
mayantha

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

Zulfiqar Ali
Guest
Zulfiqar Ali

Really nice tutorial…

mark
Guest
mark

the buffered reader worked better than System.in thanks

Fikre
Guest
Fikre

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.

mark
Guest
mark

reader worked well much better than System.in
and worked…. thanks

Prakash
Guest
Prakash

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

ANKUR
Guest
ANKUR

Same question….

philip
Guest
philip

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();

philip
Guest
philip

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.

mkyong
Guest
mkyong

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

Mike
Guest
Mike

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)

mkyong
Guest
mkyong

Thanks for your input.

Angel
Guest
Angel

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

vithalani
Guest
vithalani

great …… useful to me

Anand Raj
Guest
Anand Raj

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”

Nanda
Guest
Nanda

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

Nanda
Guest
Nanda

also can you provide which will be more efficient

Jarl
Guest
Jarl

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

Umar
Guest
Umar

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.

Umar
Guest
Umar

I mean…java.io.console…

ScanMan
Guest
ScanMan

I prefer Scanner personally. Great tutorial, thanks!

Shah
Guest
Shah

Excellent!! Very helpfull.