Search code examples
javaio

Are `InputStream` and `Reader` essentially the same, and are `OutputStream` and `Writer` essentially the same?


In Java, InputStream and OutputStream deal with byte[], and Reader and Writer with char[].

  • Do their input or output byte[] and char[] essentially have the same values? (That is my impression, because a char and a byte in IO have the same value)

  • In other words, are InputStream and Reader essentially the same, and are OutputStream and Writer essentially the same?


Solution

  • They're not essentially the same, but they do the same sorts of things for different kinds of data.

    InputStream and OutputStream work in bytes. You'd use them when dealing with non-textual information (such as an image).

    Reader and Writer work in characters. You'd use them when dealing with textual information.

    So "yes" and "no". :-) InputStream and Reader are both for reading information (a stream of bytes or a stream of characters, respectively), and OutputStream and Writer are both for writing information (a stream of bytes or a stream of characters, respectively). Which you use depends on what kind of data you're dealing with. The streams are byte-oriented. The readers/writers are character-oriented.

    There are bridging classes between the two kinds of data:

    • InputStreamReader reads from an InputStream and converts bytes to characters using a CharSet (one provided explicitly or by name).
    • OutputStreamWriter does the converse: Converts characters to bytes (again via a CharSet) and writes the bytes to an OutputStream.

    ...but most Reader/Writer subclasses read from/write to sources/destinations that are already character-based, and so don't deal with bytes at all. For instance, StringReader reads characters from a string. Since the source (the string) is already character-based, the Reader doesn't ever deal with bytes, just characters.