Main Tutorials

How to get the standard input in Java

Note
This post is duplicated, please refer to this – 3 ways to read input from console in Java.

A quick example to show you how to read the standard input in Java.


package com.mkyong.pageview;

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

public class Test {

    public static void main(String[] args) {

        BufferedReader br = null;

        try {

            // Refer to this https://mkyong.com/java/how-to-read-input-from-console-java/
            // for JDK 1.6, please use java.io.Console class to read system input.
            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();
                }
            }
        }

    }

}

About Author

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

Comments

Subscribe
Notify of
5 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Benson
10 years ago

I think Scanner is more convenient.Mkyong

mkyong
7 years ago
Reply to  Benson
Ecka
12 years ago

Is it any better or worse to use ‘System.console().readLine()’?

I think I noticed when I used the System.console() in Windows that I got some builtin console-like features (like history of commands scrollable using arrows and such) but not for Mac?

mkyong
7 years ago
Reply to  Ecka

Thanks, yes, for JDK >= 1.6, System.console().readLine() is a better much!

Balaji
11 years ago
Reply to  Ecka

You have an alternative called Console to use in JDK 1.6. This makes life easier