在Kotlin中将大型Inputstream写入File

Jef*_*ell 24 kotlin

我有一大堆从REST Web服务返回的文本,我想直接写入文件.这样做最简单的方法是什么?

我写了以下函数扩展名WORKS.但我不禁想到有一种更清洁的方法可以做到这一点.

注意:我希望使用try with resources来自动关闭流和文件

fun File.copyInputStreamToFile(inputStream: InputStream) {
    val buffer = ByteArray(1024)

    inputStream.use { input ->
        this.outputStream().use { fileOut ->

            while (true) {
                val length = input.read(buffer)
                if (length <= 0)
                    break
                fileOut.write(buffer, 0, length)
            }
            fileOut.flush()
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

yol*_*ole 60

您可以使用copyTo函数简化您的功能:

fun File.copyInputStreamToFile(inputStream: InputStream) {
    inputStream.use { input ->
        this.outputStream().use { fileOut ->
            input.copyTo(fileOut)
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 外部"使用"似乎是一个错误.您正在关闭/处置与`inputStream`打开的范围不同的范围. (4认同)
  • 为了做相反的事情(从文件写入一些输出流),我使用这个: `FileInputStream(someFile).use { stream -&gt; stream.copyTo(someOutputStream) }` ,对吧? (2认同)
  • 安德烈的评论不再相关,因为答案已被编辑 (2认同)

小智 8

我的主张是:

fun InputStream.toFile(path: String) {
    File(path).outputStream().use { this.copyTo(it) }
}
Run Code Online (Sandbox Code Playgroud)

没有关闭当前流

InputStream.toFile("/path/filename")
Run Code Online (Sandbox Code Playgroud)

另外,不要忘记处理异常,例如,如果拒绝写入权限:)


小智 6

我建议这样做:

fun InputStream.toFile(path: String) {
    use { input ->
        File(path).outputStream().use { input.copyTo(it) }
    }
}
Run Code Online (Sandbox Code Playgroud)

然后使用像:

InputStream.toFile("/some_path_to_file")
Run Code Online (Sandbox Code Playgroud)