据我所知,在Java中从文件中读取基于字符的数据的两种最常见的方法是使用Scanner或BufferedReader。我还知道BufferedReader通过使用缓冲区来避免物理磁盘操作,从而有效地读取文件。

我的问题是:

扫描器的性能和BufferedReader一样好吗? 为什么你会选择扫描器而不是BufferedReader,反之亦然?


当前回答

我更喜欢Scanner,因为它不会抛出检查异常,因此它的使用结果在一个更精简的代码。

其他回答

我建议使用BufferedReader来读取文本。扫描器隐藏IOException而BufferedReader立即抛出它。

在java中有不同的输入方式,比如:

1) BufferedReader 2) Scanner 3)命令行参数

BufferedReader从字符输入流中读取文本,缓冲字符,以便有效地读取字符、数组和行。

Where Scanner是一个简单的文本扫描程序,可以使用正则表达式解析基本类型和字符串。

如果您正在编写一个简单的日志读取器,缓冲读取器就足够了。如果您正在编写XML解析器,那么Scanner是更自然的选择。

如需更多信息,请参考:

http://java.meritcampus.com/t/240/Bufferedreader?tc=mm69

BufferedReader has significantly larger buffer memory than Scanner. Use BufferedReader if you want to get long strings from a stream, and use Scanner if you want to parse specific type of token from a stream. Scanner can use tokenize using custom delimiter and parse the stream into primitive types of data, while BufferedReader can only read and store String. BufferedReader is synchronous while Scanner is not. Use BufferedReader if you're working with multiple threads. Scanner hides IOException while BufferedReader throws it immediately.

BufferedReader和Scanner之间的区别是:

BufferedReader reads data, but Scanner parses data. You can only read String using BufferedReader, using Scanner you can read to different data types like int. BufferedReader is older than Scanner, it was added on JDK 1.1, while Scanner was added on JDK 5 release. The buffer size of BufferedReader is larger (8KB) as compared to Scanner's 1KB. BufferedReader is more suitable for reading files with long String, while Scanner is more suitable for reading small user input from command prompt. BufferedReader is synchronized, while Scanner is not, which means you cannot share Scanner among multiple threads. BufferedReader is faster than Scanner because it doesn't spend time on parsing. BufferedReader is a bit faster as compared to Scanner. BufferedReader is from java.io package, while Scanner is from java.util package.

在此基础上,我们可以选择我们的选择。

感谢阅读!

我更喜欢Scanner,因为它不会抛出检查异常,因此它的使用结果在一个更精简的代码。