I am going over input output section and there are so much classes and interfaces that I am confused a little bit.
As documentation says InputStream
is a byte based stream whereas Reader
is character-based stream. But as I understood correctly the only difference between them is that Reader
reads two bytes per time instead of one byte at a time as InputStream
does.
Therefore I don't understand is there any difference:
Using InputStream
byte[] bytes = new byte[2];
InputStream in = new FileInputStream("input.txt");
int bytesRead = in.read(bytes);
while(bytesRead != -1) {
doSomethingWithData(data);
bytesRead = inputstream.read(data);
}
Using Reader
Reader reader = new InputStreamReader(new FileInputStream("input.txt"));
int data = reader.read();
while (data != -1) {
doSomethingWithData(data);
data = reader.read();
}
I am really confusing about these aspects. Explain please in details. Thanks.
You can use a
Reader
to read text data. And it's supports some character encoding like - ISO, UTF-8. If you want to read a text file with some encoding then you can useReader
s like -BufferedReader
,StringReader
etc.And you can use
Stream (InputStream, OutputStream)
to manipulate binary data. For example you want to read a image file then you can useFileInputStream
and when you want to save it to disk then you can useFileOutputStream
.