InputStream vs InputStreamReader
They represent somewhat different things.
The InputStream
is the ancestor class of all possible streams of bytes, it is not useful by itself but all the subclasses (like the FileInputStream
that you are using) are great to deal with binary data.
On the other hand, the InputStreamReader
(and its father Reader
) are used specifically to deal with characters (so strings) so they handle charset encodings (utf8, iso-8859-1, and so on) gracefully.
The simple answer is: if you need binary data you can use an InputStream
(also a specific one like a DataInputStream
), if you need to work with text use an InputStreamReader
..
Well InputStreamReader
is used to directly read characters.
So reading them as int and then converting to char is not really optimal.
That is the main difference I believe.
InputStream
gives you the bytes, and the InputStreamReader
gives you already chars so it reads the InputStream
8bits at a time.
In addition, if you're reading big chunks of text, you can even wrap the InputStreamReader
in a BufferedReader
which provides you with some nice methods to let's say read whole lines at once.
This helping you out ?
You can also read this article: https://docs.oracle.com/javase/tutorial/essential/io/charstreams.html
Cheers,
From InputStreamReader javadoc:
A class for turning a byte stream into a character stream. Data read from the source input stream is converted into characters by either a default or a provided character converter. The default encoding is taken from the "file.encoding" system property. {@code InputStreamReader} contains a buffer of bytes read from the source stream and converts these into characters as needed.
For InputStreams, that actually contain characters in a known encoding, use the reader. Otherwise you just get the bytes and will have to do the conversion to char 'by hand'.
The difference between the two read
methods:
InputStream::read
reads a single byte
and returns it as an int
while InputStreamReader::read
reads a single char
(respecting the encoding) and returns this as an int
.
If you want to read binary data use InputStream.
If you want to read strings from a binary stream, use InputStreamReader. One of its constructors allows you to specify a character set.
For this reason do not use FileReader as it uses a platform default for a character set, which is, in many cases, not practical.