示例:将 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!
在上面的程序中,输入流是从 String 创建的,并存储在变量 stream 中。我们还需要一个字符串构建器 sb 来从流中创建字符串。
然后,我们从 InputStreamReader
创建了一个缓冲读取器 br 来从 stream 读取行。使用 while 循环,我们读取每一行并将其追加到字符串构建器。最后,我们关闭了缓冲读取器。
由于读取器可能会抛出 IOException
,因此我们在主函数中包含 throws IOException ,如下所示:
public static void main(String[] args) throws IOException