How to read input from console – Java
We can read Java’s input from “System.in” console, there are two common ways to read input from console.
1) InputStreamReader wrapped in a BufferedReader
2) Scanner classes in JDK1.5
InputStreamReader , BufferedReader example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class ReadConsoleSystem { public static void main(String[] args) { System.out.println("Enter something here : "); try{ BufferedReader bufferRead = new BufferedReader(new InputStreamReader(System.in)); String s = bufferRead.readLine(); System.out.println(s); } catch(IOException e) { e.printStackTrace(); } } } |
Scanner example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | import java.util.Scanner; public class ReadConsoleScanner { public static void main(String[] args) { System.out.println("Enter something here : "); String sWhatever; Scanner scanIn = new Scanner(System.in); sWhatever = scanIn.nextLine(); scanIn.close(); System.out.println(sWhatever); } } |
BufferedReader or Scanner
Which one is better? Should we go for BufferedReader or Scanner? I will go for BufferedReader for one reason, i familiar with it
. Well Scanner is a new class since JDK1.5, it’s come out more easy way to read input from file, and code is more clean. I may use Scanner class in my future project ~
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
Can you provide steps to simulate how you crashed the Java console?
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.
I mean…java.io.console…
I prefer Scanner personally. Great tutorial, thanks!
ya , Scanner provide many new functionality, may be i’m an old guy, used to BufferedReader already haha
Excellent!! Very helpfull.