示例: 将 InputStream 转换为字符串
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 循环,我们读取每一行并将其附加到字符串构建器。最后,我们关闭了 bufferedReader。
既然读者可以抛出
IOException
,我们在main函数中throws IOException如下:
public static void main(String[] args) throws IOException