BufferedReader vs Console vs Scanner

后端 未结 3 752
日久生厌
日久生厌 2020-12-04 09:26

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:

3条回答
  •  攒了一身酷
    2020-12-04 09:56

    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.

提交回复
热议问题