What is the difference between Reader and InputStream? And when to use what? If I can use Reader for reading characters why I will use inputstream, I guess to read objects?
Actually, Both InputStream and Reader are abstractions to read data from source, which can be either file or socket, but main difference between them is, InputStream is used to read binary data, while Reader is used to read text data, precisely Unicode characters.
The major difference between these is that the input/output stream classes read/write byte stream data. Whereas the Reader/Writer classes handle characters. The methods of input/output stream classes accept byte array as parameter whereas the Reader/Writer classes accept character array as parameter.
The InputStream is used to read data from a source and the OutputStream is used for writing data to a destination. Here is a hierarchy of classes to deal with Input and Output streams. The two important streams are FileInputStream and FileOutputStream, which would be discussed in this tutorial.
InputStream − This is used to read (sequential) data from a source. OutputStream − This is used to write data to a destination.
An InputStream is the raw method of getting information from a resource. It grabs the data byte by byte without performing any kind of translation. If you are reading image data, or any binary file, this is the stream to use.
A Reader is designed for character streams. If the information you are reading is all text, then the Reader will take care of the character decoding for you and give you unicode characters from the raw input stream. If you are reading any type of text, this is the stream to use.
You can wrap an InputStream and turn it into a Reader by using the InputStreamReader class.
Reader reader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
InputStreams are used to read bytes from a stream. So they are useful for binary data such as images, video and serialized objects.
Readers on the other hand are character streams so they are best used to read character data.
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