javajava-io

BufferedReader vs Console vs Scanner


I'm new to Java and I would like to know what is the best choice to read user input in the console. As far as I know there are three 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?


Solution

  • 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.