java InputStreamReader 与 FileReader

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7991770/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 22:35:03  来源:igfitidea点击:

InputStreamReader vs FileReader

javastream

提问by Spliff

I can't seem to determine any difference between InputStreamReaderand FileReaderbesides the way the two are initialized. Is there any benefit to using one or the other? Most other articles cover FileInputStreamvs InputStreamReader, but I am contrasting with FileReaderinstead. Seems to me they both have the same purpose.

我似乎无法确定任何区别InputStreamReaderFileReader另外两个被初始化的方式。使用其中一种有什么好处吗?大多数其他文章都涵盖FileInputStreamvs InputStreamReader,但我与之形成对比FileReader。在我看来,他们都有相同的目的。

回答by Michael Borgwardt

First, InputStreamReadercan handle all input streams, not just files. Other examples are network connections, classpath resources and ZIP files.

首先,InputStreamReader可以处理所有输入流,而不仅仅是文件。其他示例包括网络连接、类路径资源和 ZIP 文件。

Second, FileReaderuntil Java 11 did not allow you to specify an encoding and instead only used the plaform default encoding, which made it pretty much useless as using it would result in corrupted data when the code is run on systems with different platform default encodings.

其次,FileReader直到 Java 11 不允许您指定编码,而仅使用平台默认编码,这使得它几乎无用,因为当代码在具有不同平台默认编码的系统上运行时,使用它会导致数据损坏。

Since Java 11, FileReaderis a useful shortcut for wrapping an InputStreamReaderaround a FileInputStream.

从 Java 11 开始,FileReaderInputStreamReaderFileInputStream.

回答by JB Nizet

FileReader reads character from a file in the file system. InputStreamReader reads characters from any kind of input stream. The stream cound be a FileInputStream, but could also be a stream obtained from a socket, an HTTP connection, a database blob, whatever.

FileReader 从文件系统中的文件读取字符。InputStreamReader 从任何类型的输入流中读取字符。流可以是 FileInputStream,但也可以是从套接字、HTTP 连接、数据库 blob 等获取的流。

I usually prefer using an InputStreamReader wrapping a FileInputStream to read from a file because it allows specifying a specific character encoding.

我通常更喜欢使用 InputStreamReader 包装 FileInputStream 来读取文件,因为它允许指定特定的字符编码。

回答by Peter Lawrey

FileReader extends InputStreamReader. The only differences is that FileReader has constructors which assume you are reading from a file such as String filename, File fileand FileDescriptor fd

FileReader 扩展了 InputStreamReader。唯一的区别是 FileReader 的构造函数假设您正在从文件中读取,例如String filename,File fileFileDescriptor fd

I suggest you have a look at the source for FileReader to know more.

我建议您查看 FileReader 的来源以了解更多信息。