InputStreamReader
时间: 2023-10-25 20:24:27 浏览: 47
InputStream
4星 · 用户满意度95%
The InputStreamReader class is a subclass of the Reader class in Java. It reads bytes from an InputStream and decodes them into characters using a specified character encoding. The decoded characters are then made available to the programmer as a stream of characters.
The InputStreamReader class is used when we want to read data from an InputStream and process it as text. It provides a convenient way to convert binary data into text data.
Here is an example of using an InputStreamReader to read data from an InputStream:
```java
InputStream inputStream = new FileInputStream("data.txt");
InputStreamReader reader = new InputStreamReader(inputStream, "UTF-8");
int data = reader.read();
while (data != -1) {
char ch = (char) data;
System.out.print(ch);
data = reader.read();
}
reader.close();
inputStream.close();
```
In this example, we create an InputStream from a file called "data.txt". We then create an InputStreamReader using the UTF-8 character encoding. We read data from the InputStreamReader one character at a time using the read() method. The read() method returns -1 when the end of the stream is reached. Finally, we close the InputStreamReader and the InputStream.
阅读全文