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

我的问题是:

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


当前回答

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

其他回答

BufferedReader可能会给你更好的性能(因为Scanner是基于InputStreamReader,查看源代码)。哎呀,对于从文件中读取数据,它使用nio。当我测试nio的性能与大文件的BufferedReader性能时,nio显示出更好的性能。 要从文件中读取数据,请尝试Apache Commons IO。

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

BufferedReader和Scanner的区别如下:

BufferedReader已同步,但Scanner未同步。 BufferedReader是线程安全的,但Scanner不是。 BufferedReader有更大的缓冲内存,而Scanner有更小的缓冲内存。 BufferedReader执行速度更快,但Scanner执行速度较慢。 从控制台读取一行的代码:

BufferedReader:

InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
String st = br.readLine();
       
// You can make the object InputStreamReader object inside the BufferReader method.
BufferReader br = new BufferedReader(InputStreamReader(System.in));
String st = br.readLine();

// You can even inspect the type of the input stream manually by using Parse method which accepts string parameter.
int x = Integer.parseInt(br.readLine());

// Or you can pass the object directly.
int x = Integer.parseInt(st);

扫描仪:

Scanner sc = new Scanner(System.in);
String st = sc.nextLine();

Scanner用于解析来自流内容的令牌,而BufferedReader只读取流,不做任何特殊的解析。

事实上,您可以将BufferedReader传递给扫描器作为要解析的字符源。

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.

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

感谢阅读!