How to read input from console – Java
Written on December 11, 2008 at 4:13 pm by
mkyong
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 article was posted in Java category.
All Java Tutorials
- Java Core Technology - Java RegEx, Java XML, Java I/O, Java Misc
- J2EE Frameworks - Hibernate, Spring 2.5, Spring MVC, Struts 1.x, Struts 2.x
- Build Tools - Maven, Archiva
- Unit Test - jUnit, TestNG
- Client Scripts - jQuery
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.