Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
223 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...