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.
FileInputStream is Byte Based, it can be used to read bytes. FileReader is Character Based, it can be used to read characters. FileInputStream is used for reading binary files. FileReader is used for reading text files in platform default encoding.
FileReader is used to read a file from a disk drive whereas BufferedReader is not bound to only reading files. It can be used to read data from any character stream.
BufferedReader reads a couple of characters from the Input Stream and stores them in a buffer. InputStreamReader reads only one character from the input stream and the remaining characters still remain in the streams hence There is no buffer in this case.
An InputStreamReader is a bridge from byte streams to character streams: It reads bytes and decodes them into characters using a specified charset . The charset that it uses may be specified by name or may be given explicitly, or the platform's default charset may be accepted.
First, InputStreamReader
can handle all input streams, not just files. Other examples are network connections, classpath resources and ZIP files.
Second, FileReader
until 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.
Since Java 11, FileReader
is a useful shortcut for wrapping an InputStreamReader
around a FileInputStream
.
FileReader reads character from a file in the file system. InputStreamReader reads characters from any kind of input stream. The stream could 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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With