# 如何在 Java 中将`InputStream`转换为字符串

> 原文： [https://beginnersbook.com/2013/12/how-to-convert-inputstream-to-string-in-java/](https://beginnersbook.com/2013/12/how-to-convert-inputstream-to-string-in-java/)

以下是如何读取`InputStream`并将其转换为`String`的完整示例。涉及的步骤是：

1）我使用[`getBytes()`方法](https://beginnersbook.com/2013/12/java-string-getbytes-method-example/) 将文件内容转换为字节之后，使用包含内部缓冲区的`ByteArrayInputStream`初始化`InputStream`，缓冲区包含可以从流中读取的字节。

2）使用`InputStreamReader`读取`InputStream` 。

3）使用`BufferedReader`读取`InputStreamReader`。

4）将`BufferedReader`读取的每一行附加到`StringBuilder`对象上。

5）最后使用`toString()`方法将`StringBuilder`转换为`String`。

```java
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class Example {
   public static void main(String[] args) throws IOException {
       InputStreamReader isr = null;
       BufferedReader br = null;
       InputStream is = 
            new ByteArrayInputStream("This is the content of my file".getBytes());
       StringBuilder sb = new StringBuilder();
       String content;
       try {
           isr = new InputStreamReader(is);
	   br = new BufferedReader(isr);
	   while ((content = br.readLine()) != null) {
		sb.append(content);
	   }
	} catch (IOException ioe) {
		System.out.println("IO Exception occurred");
		ioe.printStackTrace();	
	   } finally {
		isr.close();
		br.close();
	      }
        String mystring = sb.toString();
	System.out.println(mystring);
   }
}
```

输出：

```java
This is the content of my file
```

#### 参考：

*   [`BufferedReader`](https://docs.oracle.com/javase/7/docs/api/java/io/BufferedReader.html)
*   [`ByteArrayInputStream`](https://docs.oracle.com/javase/7/docs/api/java/io/ByteArrayInputStream.html)
*   [`InputStream`](https://docs.oracle.com/javase/7/docs/api/java/io/InputStream.html)
*   [`InputStreamReader`](https://docs.oracle.com/javase/7/docs/api/java/io/InputStreamReader.html)