Reading from Console: JAVA Scanner vs BufferedReader
When read an input from console, there are two options exists to achive that. First using Scanner, last using BufferedReader. Both of them have different characteristics. It means differences how to use it.
Scanner treated given input as token. BufferedReader just read line by line given input as string. Scanner it self provide parsing capabilities just like nextInt(), nextFloat().
But, what is others differences between?
- Scanner treated given input as token. BufferedReader as stream line/String
- Scanner tokenized given input using regex. Using BufferedReader must write extra code
- BufferedReader faster than Scanner *point no. 2
- Scanner isn’t synchronized, BufferedReader synchronized
Scanner come with since JDK version 1.5 higher.
When should use Scanner, or Buffered Reader?
Look at the main differences between both of them, one using tokenized, others using stream line. When you need parsing capabilities, use Scanner instead. But, i am more comfortable with BufferedReader. When you need to read from a File, use BufferedReader, because it’s use buffer when read a file. Or you can use BufferedReader as input to Scanner.