inputstream转write
时间: 2023-12-13 22:03:55 浏览: 116
将一个 `InputStream` 对象转换为 `Writer` 对象的过程,需要经过以下步骤:
1. 创建 `InputStreamReader` 对象,并指定要读取的 `InputStream` 和字符编码(如 UTF-8)。
```java
InputStreamReader isr = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
```
2. 创建 `BufferedReader` 对象,并将 `InputStreamReader` 对象作为参数传入。
```java
BufferedReader reader = new BufferedReader(isr);
```
3. 创建 `StringWriter` 对象,用于保存读取的数据。
```java
StringWriter writer = new StringWriter();
```
4. 创建 `char` 数组,用于保存读取的数据。
```java
char[] buffer = new char[1024];
```
5. 循环读取数据,并将数据写入 `StringWriter` 对象中。
```java
int length;
while ((length = reader.read(buffer)) != -1) {
writer.write(buffer, 0, length);
}
```
6. 关闭 `BufferedReader` 和 `InputStreamReader` 对象。
```java
reader.close();
isr.close();
```
7. 获取写入的数据。
```java
String result = writer.toString();
```
完整的代码示例:
```java
public static String inputStreamToString(InputStream inputStream) throws IOException {
InputStreamReader isr = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
BufferedReader reader = new BufferedReader(isr);
StringWriter writer = new StringWriter();
char[] buffer = new char[1024];
int length;
while ((length = reader.read(buffer)) != -1) {
writer.write(buffer, 0, length);
}
reader.close();
isr.close();
return writer.toString();
}
```
阅读全文