InputStreamReader vs FileReader

2019-03-09 00:13发布

问题:

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.

回答1:

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.



回答2:

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.



回答3:

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.



标签: java stream