Development Tip

Kotlin에서 InputStream의 전체 콘텐츠를 문자열로 읽으려면 어떻게해야하나요?

yourdevel 2020. 10. 4. 13:33
반응형

Kotlin에서 InputStream의 전체 콘텐츠를 문자열로 읽으려면 어떻게해야하나요?


최근 InputStream에 Kotlin에서 의 전체 내용을 문자열로 읽는 코드를 보았습니다 .

// input is of type InputStream
val baos = ByteArrayOutputStream()
input.use { it.copyTo(baos) }
val inputAsString = baos.toString()

그리고 또한:

val reader = BufferedReader(InputStreamReader(input))
try {
    val results = StringBuilder()
    while (true) { 
        val line = reader.readLine()
        if (line == null) break
        results.append(line) 
    }
    val inputAsString = results.toString()
} finally {
    reader.close()
}

그리고 이것은 자동으로 닫히기 때문에 더 부드럽게 보입니다 InputStream.

val inputString = BufferedReader(InputStreamReader(input)).useLines { lines ->
    val results = StringBuilder()
    lines.forEach { results.append(it) }
    results.toString()
}

또는 약간의 변형 :

val results = StringBuilder()
BufferedReader(InputStreamReader(input)).forEachLine { results.append(it) }
val resultsAsString = results.toString()   

그런 다음이 기능적 폴드 물건 :

val inputString = input.bufferedReader().useLines { lines ->
    lines.fold(StringBuilder()) { buff, line -> buff.append(line) }.toString()
}

또는 다음을 닫지 않는 잘못된 변형 InputStream:

val inputString = BufferedReader(InputStreamReader(input))
        .lineSequence()
        .fold(StringBuilder()) { buff, line -> buff.append(line) }
        .toString()

그러나 그들은 모두 투박하고 나는 동일한 버전의 새롭고 다른 버전을 계속 찾고 있습니다 ... 그리고 그들 중 일부는 InputStream. 을 읽는 비 투잡 한 (관용적) 방법은 InputStream무엇입니까?

참고 : 이 질문은 작성자 ( Self-Answered Questions ) 가 의도적으로 작성하고 답변 하므로 일반적으로 묻는 Kotlin 주제에 대한 관용적 답변이 SO에 있습니다.


Kotlin에는 이러한 목적을위한 특정 확장 기능이 있습니다.

가장 간단한 방법 :

val inputAsString = input.bufferedReader().use { it.readText() }  // defaults to UTF-8

그리고이 예제에서 당신은 사이에 결정할 수 bufferedReader()하거나 reader(). 함수 호출 Closeable.use()은 람다 실행이 끝날 때 입력을 자동으로 닫습니다.

추가 읽기 :

이런 종류의 일을 많이하면 확장 함수로 작성할 수 있습니다.

fun InputStream.readTextAndClose(charset: Charset = Charsets.UTF_8): String {
    return this.bufferedReader(charset).use { it.readText() }
}

그러면 다음과 같이 쉽게 호출 할 수 있습니다.

val inputAsString = input.readTextAndClose()  // defaults to UTF-8

On a side note, all Kotlin extension functions that require knowing the charset already default to UTF-8, so if you require a different encoding you need to adjust the code above in calls to include an encoding for reader(charset) or bufferedReader(charset).

Warning: You might see examples that are shorter:

val inputAsString = input.reader().readText() 

But these do not close the stream. Make sure you check the API documentation for all of the IO functions you use to be sure which ones close and which do not. Usually if they include the word use (such as useLines() or use()) thy close the stream after. An exception is that File.readText() differs from Reader.readText() in that the former does not leave anything open and the latter does indeed require an explicit close.

See also: Kotlin IO related extension functions


An example that reads contents of an InputStream to a String

import java.io.File
import java.io.InputStream
import java.nio.charset.Charset

fun main(args: Array<String>) {
    val file = File("input"+File.separator+"contents.txt")
    var ins:InputStream = file.inputStream()
    var content = ins.readBytes().toString(Charset.defaultCharset())
    println(content)
}

For Reference - Kotlin Read File

참고URL : https://stackoverflow.com/questions/39500045/in-kotlin-how-do-i-read-the-entire-contents-of-an-inputstream-into-a-string

반응형