How to get input from Java Console
input
java
console
System.console
scanner
BufferedReader
InputStreamReader
This tutorial will show how to read user input when creating a console application.
Here are three methods how to read from console:
- System.console
- Scanner
- BufferedReader + InputStreamReader
All examples will exit if quit is typed.
System.console
package com.admfactory.console;
public class Console1 {
public static void main(String[] args) {
System.out.println("Console example using System.console");
while (true) {
System.out.print("Input: ");
String text = System.console().readLine();
if (text.equalsIgnoreCase("quit")) {
System.out.println("Exit.");
break;
}
System.out.println("input : " + text);
}
}
}
Note: The problem with using this method is that it will not run properly using an IDE. The console will be null and the application will throw the following error:
Console example using System.console
Input: Exception in thread "main" java.lang.NullPointerException
at com.admfactory.console.Console1.main(Console1.java:8)
Output
Console example using System.console
Input: test
text: test
Input: quit
Exit.
Scanner
package com.admfactory.console;
import java.util.Scanner;
public class Console2 {
public static void main(String[] args) {
System.out.println("Console example using Scanner");
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.print("Input: ");
String text = scanner.nextLine();
if (text.equalsIgnoreCase("quit")) {
System.out.println("Exit.");
break;
}
System.out.println("text: " + text);
}
scanner.close();
}
}
Output
Console example using Scanner
Input: test
text: test
Input: quit
Exit.
BufferedReader + InputStreamReader
package com.admfactory.console;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Console3 {
public static void main(String[] args) {
System.out.println("Console example using BufferedReader and InputStreamReader");
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(System.in));
while (true) {
System.out.print("Input: ");
String text = br.readLine();
if (text.equalsIgnoreCase("quit")) {
System.out.println("Exit.");
break;
}
System.out.println("text: " + text);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
/** closing the BufferedReader object */
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
Output
Console example using BufferedReader and InputStreamReader
Input: test
text: test
Input: quit
Exit.