BufferedReader vs Console vs Scanner

2019-01-12 22:02发布

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 java-io
3条回答
ら.Afraid
2楼-- · 2019-01-12 22:15

BufferedReader

  • Since Java 1.1
  • Throws checked exceptions
  • Can read chars, char arrays, and lines
  • Fast

Scanner

  • Since Java 1.5
  • Doesn't throw checked exceptions
  • Can read lines, whitespace-delimited tokens, regex-delimited tokens, and numbers
  • Difficult to read single characters

Console

  • Since Java 1.6
  • Doesn't throw checked exceptions
  • Can read lines
  • Underlying reader can read chars and char arrays (stops at line bounds)
  • Not always available (e.g. Eclipse)
  • Can read passwords (i.e. read without displaying the characters)

Recommendation: Scanner

The methods for reading numbers are very useful. The exceptions are unchecked, so you do not have to write boilerplate try/catch blocks.

查看更多
别忘想泡老子
3楼-- · 2019-01-12 22:17

Console class tries to implement a platform independent way to handle with console input. All OS has a console in any way, but they are quiet diferent in implementation. So Console class gives you a Java platfrom 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.

查看更多
疯言疯语
4楼-- · 2019-01-12 22:18

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/

查看更多
登录 后发表回答