Skip to content

Latest commit

 

History

History
48 lines (31 loc) · 1.54 KB

File metadata and controls

48 lines (31 loc) · 1.54 KB

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

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

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

示例:将InputStream转换为String

import java.io.*

fun main(args: Array<String>) {

    val stream = ByteArrayInputStream("Hello there!".toByteArray())
    val sb = StringBuilder()
    var line: String?

    val br = BufferedReader(InputStreamReader(stream))
    line = br.readLine()

    while (line != null) {
        sb.append(line)
        line = br.readLine()
    }
    br.close()

    println(sb)

}

运行程序时,输出为:

Hello there!

在上述程序中,输入流是从字符串创建的,并存储在变量stream中。 我们还需要字符串构建器sb从流中创建字符串。

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

因为,读者可以抛出IOException,所以我们在主函数中将抛出IOException如下:

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

以下是等效的 Java 代码:InputStream转换为String的 Java 程序