Author: Jakob Jenkov Translator: Li Jing ([email protected])
This section provides a brief introduction to InputStreamReader and OutputStreamWriter. The attentive reader may find that in the previous article, the classes in IO either end with a stream or end in reader or writer, what is the purpose of these two classes that end with the class name suffix of the byte stream and the character stream? Simply put, these two classes convert bytes into character streams, with data conversion in between, similar to the idea of adapter mode.
InputStreamReader
Original link
The InputStreamReader will contain a inputstream, which will allow the input byte stream to be converted into character streams, code examples:
01 |
InputStream inputStream = new FileInputStream( "c:\\data\\input.txt" ); |
03 |
Reader reader = new InputStreamReader(inputStream); |
05 |
int data = reader.read(); |
09 |
char theChar = ( char ) data; |
Note: For clarity, the code ignores some of the necessary exception handling. For more information about exception handling, refer to Java IO exception handling.
The Read () method returns a variable of type int that contains the contents of the read character (translator note: 0~65535). The code is as follows:
1 |
int data = reader.read(); |
You can convert the returned int value to a char variable, like this:
1 |
char aChar = ( char ) data; //译者注:这里不会造成数据丢失,因为返回的int类型变量data只有低16位有数据,高16位没有数据 |
If the method returns-1, indicating that there are no remaining readable characters in reader, you can turn reader off. 1 is an int type, not a byte or char type, which is not the same.
InputStreamReader also has other optional constructors that allow you to specify the stream of characters that the underlying stream of bytes will be interpreted as encoded. Examples are as follows:
1 |
InputStream inputStream = new FileInputStream( "c:\\data\\input.txt" ); |
3 |
Reader reader = new InputStreamReader(inputStream, "UTF-8" ); |
Note the second parameter of the constructor, at which point the InputStreamReader converts the bytes of the input into a stream of UTF8 characters.
OutputStreamWriter
Original link
The OutputStreamWriter will contain a outputstream, which allows the output byte stream to be converted into a character flow with the following code:
1 |
OutputStream outputStream = new FileOutputStream( "c:\\data\\output.txt" ); |
3 |
Writer writer = new OutputStreamWriter(outputStream); |
5 |
writer.write( "Hello World" ); |
The OutputStreamWriter also has a constructor that converts the output byte flow into a character stream of the specified encoding.
original articles, reproduced please specify: reproduced from the Concurrent programming network –ifeve.com This article link address: Java Io:inputstreamreader and OutputStreamWriter
Java Io:inputstreamreader and OutputStreamWriter