0

inputsteam reads a byte each time, and inputstreamreader can convert byte to characher, and then reads a character each time, and reader also reads a character each time, so what is the difference between them?

1

3 Answers 3

1

The InputStreamReader handles the encoding. A character does not always fit into a byte(8bit) and the byte value does not always map to the same char, the java char for example uses 16bit to encode a character which makes it possible to represent a greater number of different characters.

Depending on the source of the InputStream a character may be encoded with ASCII(1 byte), UTF-8(1 or more byte), UTF-16(2 or 4 byte), utf-32(4 byte) or any other existing encoding. Given the right Charset a Reader can convert the raw bytes into the corresponding java character.

Sign up to request clarification or add additional context in comments.

Comments

0

From the JavaDocs:

Input Stream: This abstract class is the superclass of all classes representing an input stream of bytes

Input Stream Reader: a bridge from byte streams to character streams: It reads bytes and decodes them into characters using a specified charset

The stream just gives you the raw bytes, the reader can convert the raw bytes into characters for different encodings (ASCII/ISO/UTF).

http://download.oracle.com/javase/6/docs/api/java/io/InputStream.html http://download.oracle.com/javase/6/docs/api/java/io/InputStreamReader.html http://download.oracle.com/javase/6/docs/api/java/nio/charset/Charset.html

1 Comment

It's worth mentioning that one should usually NEVER use things like FileReader/FileWriter etc by themselves, because they always use the default encoding, which is often what you don't want. Usually you do fs=new FileInputStream and wrap that in InputStreamReader(fs,"UTF-8") or whatever.
0

InputStreamReader is an implementation of the abstract class Reader that reads character from an InputStream, converting bytes according to a given charset. There are other implementations of Reader too, for example StringReader which return character from a string and does not need any charset conversion.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.