BufferedReader vs Console vs Scanner

JavaJava Io

Java Problem Overview


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:

  1. Console console = System.console();
  2. BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
  3. Scanner reader = new Scanner(System.in);

Which one should I choose? Why that one and not the other ones?

Java Solutions


Solution 1 - Java

BufferedReader
Scanner
Console
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.

Solution 2 - Java

Console class is implemented in a platform independent way to handle the console input for different Os. All OS has a console/shell but they are quite different in implementation. So Console class gives you a Java platform independent runtime class to access things like password input, etc.

Scanner is used for parsing tokens from the contents of the stream while BufferedReader just reads the stream and does not do any special parsing.

Solution 3 - Java

beside these you can also use datainputstream etc.

Now BufferedReader Read text from a character-input stream, buffering characters so as to provide for the efficient reading of characters, arrays, and lines. The buffer size may be specified, or the default size may be used. The default is large enough for most purposes.

Where Scanner is a simple text scanner which can parse primitive types and strings using regular expressions. A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace. The resulting tokens may then be converted into values of different types using the various next methods. Scanner is used for parsing tokens from the contents of the stream while BufferedReader just reads the stream and does not do any special parsing.

also check the below link it will surely help you.......

http://www.javawebtips.com/50474/

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionVictor Castillo TorresView Question on Stackoverflow
Solution 1 - JavatomView Answer on Stackoverflow
Solution 2 - JavaJuned AhsanView Answer on Stackoverflow
Solution 3 - JavaroanjainView Answer on Stackoverflow