Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
226 views
in Technique[技术] by (71.8m points)

java - BufferedReader vs Console vs Scanner

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...