Skip to content

Latest commit

 

History

History
46 lines (30 loc) · 1.49 KB

File metadata and controls

46 lines (30 loc) · 1.49 KB

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

原文: https://www.programiz.com/java-programming/examples/convert-inputstream-string

在此程序中,您将学习如何使用 Java 中的InputStreamReader将输入流转换为字符串。

示例:将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循环,我们读取每一行并将其附加到字符串生成器。 最后,我们关闭了bufferedReader

因为,Reader可以抛出IOException,所以我们在main函数中将抛出IOException如下:

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