跳到主要内容

Java 程序:将InputStream转换为字符串

要理解此示例,你应该具备以下 Java 编程主题的知识:

示例:将 InputStream 转换为 String

import java.io.*;

public class InputStreamString {

public static void main(String[] args) throws IOException {

InputStream stream = new ByteArrayInputStream("Hello there!".getBytes());
StringBuilder sb = new StringBuilder();
String line;

BufferedReader br = new BufferedReader(new InputStreamReader(stream));
while ((line = br.readLine()) != null) {
sb.append(line);
}
br.close();

System.out.println(sb);

}
}

输出

Hello there!

在上述程序中,我们从字符串创建了输入流并将其存储在变量 stream 中。我们还需要一个字符串构建器 sb 来从流中创建字符串。

然后,我们从 InputStreamReader 创建了一个缓冲读取器 br,以从 stream 读取行。使用一个 while 循环,我们读取每一行并将其附加到字符串构建器上。最后,我们关闭了缓冲读取器。

由于读取器可能抛出 IOException,因此我们在 main 函数中使用了如下的 throws IOException

public static void main(String[] args) throws IOException