How to Read Input from Console in Java


In this example we will show 3 ways to read input from a console in Java.

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

Source Code

1)

package com.beginner.examples;
import java.util.Scanner;
public class InputFromConsole1 {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner scanner = new Scanner(System.in);
        while (true) {
            System.out.println("Please enter content or enter "b" to exit:");
            String strInput = scanner.next();
            if (strInput.equals("b")) {
                scanner.close();
                break;
            } else {
                System.out.println("Your input is:" + strInput);
            }

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

}

Output:

Please enter content or enter "b" to exit:
Hello!
Your input is:Hello!
Please enter content or enter "b" to exit:
b
over!

2)

package com.beginner.examples;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class InputFromConsole2 {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            System.out.println("Enter content:");
            String str = br.readLine();
            System.out.println("Your input is: " + str);
        } catch (IOException e) {
            // TODO: handle exception
            e.printStackTrace();
        }

    }

}

Output:

Enter content:
Hello!
Your input is: Hello!

Tips

In JDK 1.5, the developer starts to use java.util.Scanner to read system input.
In JDK 1.6, the developer starts to switch to the more simple and powerful java.io.Console class.

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments