Scanner vs. BufferedReader

前端 未结 12 1771
死守一世寂寞
死守一世寂寞 2020-11-22 02:17

As far I know, the two most common methods of reading character-based data from a file in Java is using Scanner or BufferedReader. I also know that

12条回答
  •  后悔当初
    2020-11-22 02:55

    The answer below is taken from Reading from Console: JAVA Scanner vs BufferedReader

    When read an input from console, there are two options exists to achieve that. First using Scanner, another 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.

提交回复
热议问题