Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should I use InputStreamReader and OutputStreamWriter?

From the Java Tutorial site, we know InputStreamReader and OutputStreamWriter can convert streams between bytes and characters.

InputStreamReader converts bytes read from input to characters, while OutputStreamWriter converts characters to bytes to output.

But when should I use this two classes?

We have Inputstream/OutputStream input/output byte by byte, and Reader/Writer input/output character by character.

So when using InputStreamReader to input characters from byte stream, why not just use Reader class (or its sub classes) to read character directly? Why not use OutputStream instead of OutputStreamWriter to write bytes directly?


EDIT: When do I need to convert streams between bytes and characters using InputStreamReader and OutputStreamWriter?


EDIT: Under which circumstances should I care about encoding scheme?

like image 258
Zachary Avatar asked May 16 '13 05:05

Zachary


1 Answers

To understand the purpose of this, you need to get the following firmly into your mind. In Java char and String are for "text" expressed as Unicode, and byte or byte[] are for binary data. Bytes are NOT text. Bytes can represent encoded text ... but they have to be decoded before you can use the char and String types on them.

So when using InputStreamReader to input characters from byte stream, why not just use Reader class (or its sub classes) to read character directly?

(InputStreamReader is a subclass of Reader, so it not a case of "either ... or ...".)

The purpose of the InputStreamReader is to adapt an InputStream to a Reader. This adapter takes care of decoding the text from bytes to chars which contain Unicode codepoints1.

So you would use it when you have an existing InputStream (e.g. from a socket) ... or when you need more control over the selection of the encoding scheme. (Re the latter - you can open a file directly using FileReader, but that implicitly uses the default platforming encoding for the file. By using FileInputStream -> InputStreamReader you can specify the encoding scheme explicitly.)

Why not use OutputStream instead of OutputStreamWriter to write bytes directly?

Its encodings again. If you want write text to an OUtputStream, you have to encode it according to some encoding scheme; e.g.

    os.write(str.getBytes("UTF-8"));

By using a Writer, you move the encoding into the output pipeline where it is less obtrusive, and can typically be done more efficiently.


1 - or more strictly, a 16-bit representation of Unicode codepoints.

like image 148
Stephen C Avatar answered Sep 29 '22 08:09

Stephen C