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

    }

}

5 comments on “How to get the standard input in Java

  1. 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?

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

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

      Reply

Leave a Comment

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