InputStreamReader vs FileReader

2019-03-09 00:52发布

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

标签: java stream
3条回答
小情绪 Triste *
2楼-- · 2019-03-09 01:07

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

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

查看更多
一纸荒年 Trace。
3楼-- · 2019-03-09 01:14

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

Second, FileReader does not allow you to specify an encoding and instead uses the plaform default encoding, which makes it pretty much useless as using it will result in corrupted data when the code is run on systems with different platform default encodings.

In short, forget that FileReader exists.

查看更多
做自己的国王
4楼-- · 2019-03-09 01:18

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.

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

查看更多
登录 后发表回答