Hi I’m new to Java
and I would like to know what is the best choice to read a user Input in the console, as far as I know there are 3 ways to do it:
Console console = System.console();
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
Scanner reader = new Scanner(System.in);
Which one should I choose? Why that one and not the other ones?
Advertisement
Answer
BufferedReader
- Since Java 1.1
- Throws checked exceptions
- Can read single chars, char arrays, and lines
- Fast
Scanner
- Since Java 1.5
- Throws unchecked exceptions
- Can read lines, numbers, whitespace-delimited tokens, regex-delimited tokens
- Difficult to read single characters
Console
- Since Java 1.6
- Throws unchecked exceptions
- Not always available (e.g. if input/output is redirected, and in Eclipse)
- Can read lines
- Underlying reader can read single chars and char arrays (but stops at line bounds)
- Can read passwords (i.e. read without displaying the characters)
Recommendation: Scanner
The methods for reading numbers are very useful (though beware when using nextInt() etc. followed by nextLine()). The exceptions are unchecked, so you do not have to write boilerplate try/catch blocks.