English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Tutoriel de base Java

Java 流程控制

Java 数组

Java 面向对象(I)

Java 面向对象(II)

Java 面向对象(III)

Gestion des exceptions Java

Java 列表(List)

Java Queue(队列)

Java Map集合

Java Set集合

Java 输入输出(I/O)

Java Reader/Writer

Java 其他主题

Java程序将InputStream转换为字符串

Comprehensive Java Examples

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

示例:将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);
    }
}

When the program is run, the output is:

Hello there!

In the above program, the input stream is created from String and stored in the variable stream. We also need a string builder sb to create a string from the stream.

Then, we create a buffered reader br from InputStreamReader to read lines from the stream. Using a while loop, we read each line and append it to the string builder. Finally, we close the bufferedReader.

Because the reader can throw IOException, we haveIOException is thrown:

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

Comprehensive Java Examples