Java 缓冲阅读器和文件阅读器和扫描器类之间的区别
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20838244/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Difference between buffered reader and file reader and scanner class
提问by Charbel
Can anyone explain me the difference between the class BufferedReader, FileReaderand Scanner? and which one to use when I want to read a text file?
任何人都可以向我解释类之间的区别BufferedReader,FileReader和Scanner?当我想阅读文本文件时使用哪一个?
采纳答案by Jon Skeet
Well:
好:
FileReaderis just aReaderwhich reads a file, using the platform-default encoding (urgh)BufferedReaderis a wrapper around anotherReader, adding buffering and the ability to read a line at a timeScannerreads from a variety of different sources, but is typically used for interactive input. Personally I find the API ofScannerto be pretty painful and obscure.
FileReader只是一个Reader读取文件,使用平台默认编码(urgh)BufferedReader是另一个的包装器Reader,添加缓冲和一次读取一行的能力Scanner从各种不同的来源读取,但通常用于交互式输入。我个人认为 的 APIScanner非常痛苦和晦涩。
To read a text file, I would suggest using a FileInputStreamwrapped in an InputStreamReader(so you can specify the encoding) and then wrapped in a BufferedReaderfor buffering and the ability to read a line at a time.
要读取文本文件,我建议使用FileInputStream包装在 an 中InputStreamReader(以便您可以指定编码),然后包装在 a 中BufferedReader用于缓冲和一次读取一行的能力。
Alternatively, you could use a third-party library which makes it simpler, such as Guava:
或者,您可以使用第三方库使其更简单,例如Guava:
File file = new File("foo.txt");
List<String> lines = Files.readLines(file, Charsets.UTF_8);
Or if you're using Java 7, it's already available for you in java.nio.file.Files:
或者,如果您使用的是 Java 7,它已经可以在以下位置使用java.nio.file.Files:
Path path = FileSystems.getDefault().getPath("foo.txt");
List<String> lines = Files.readAllLines(path, StandardCharsets.UTF_8);
回答by Saurabh Sharma
And as per your question for reading a text file you should use BufferedReaderbecause Scannerhides IOExceptionwhile BufferedReaderthrowsit immediately.
根据您阅读文本文件的问题,您应该使用,BufferedReader因为在立即抛出时Scanner隐藏IOException。BufferedReader
BufferedReaderis synchronizedand Scanneris not.
BufferedReader是同步的,Scanner不是。
Scanneris used for parsing tokens from the contents of the stream.
Scanner用于从流的内容中解析标记。
BufferedReaderjust reads the stream.
BufferedReader只读取流。
For more info follow the link (http://en.allexperts.com/q/Java-1046/2009/2/Difference-Scanner-Method-Buffered.htm)
有关更多信息,请点击链接(http://en.allexperts.com/q/Java-1046/2009/2/Difference-Scanner-Method-Buffered.htm)

