20

Today I got this question for which I think I answered very bad. I said stream is a data that flows and reader is a technique where we read from that is a static data. I know this is an awful answer, so please provide me the crisp difference and definitions between these two with example in Java.

Thanks.

bragboy
  • 34,892
  • 30
  • 114
  • 171

4 Answers4

21

An InputStream is byte-oriented. A Reader is character-oriented.

The javadocs are your friend, explaining the difference. Reader, InputStream

Community
  • 1
  • 1
brabster
  • 42,504
  • 27
  • 146
  • 186
14

As others have said, the use cases for each are slightly different (even though they often can be used interchangeably)

Since readers are for reading characters, they are better when you are dealing with input that is of a textual nature (or data represented as characters). I say better because Readers (in the context of typical usage) are essentially streams with methods that easily facilitate reading character input.

Tom Neyland
  • 6,860
  • 2
  • 36
  • 52
  • 1
    +1 that is really the point, a Reader is generally backed by an InputStream of some sort (not always - see StringReader) and performing a conversion of bytes to 16 bit unicode characters. – Yishai Mar 11 '10 at 19:56
9

Stream is for reading bytes, Reader is for reading characters. One character may take one byte or more, depending on character set.

Peter Štibraný
  • 32,463
  • 16
  • 90
  • 116
  • 1
    When reading from stream, mapping between bytes and characters is given by encoding. For UTF-8 one character can be between 1 to 6 bytes. – Peter Štibraný Jan 28 '14 at 10:07
7

Stream classes are byte-oriented classes, that mean all InputStream classes (Buffered and non-buffered) read data byte by byte from stream and all OutputStream(Buffered and non-buffered) classes writes data byte by byte to the stream. Stream classes are useful when you have small data or if you are dealing with binary files like images.

On the other handReader/Writer are character based classes. These classes read or write one character at time from or into stream. These classes extends either java.io.Reader (all character input classes) or java.io.Writer (all character output classes). These classes are useful if you are dealing with text file or other textual stream. These classes are also Buffered and Non-Buffered.

Sachin Kumar
  • 781
  • 1
  • 9
  • 28