我从REST web服务返回了大量文本,我想直接将其写入文件.最简单的方法是什么?
我已经编写了以下有效的函数扩展.但我忍不住想,有一种更干净的方法可以做到这一点.
Note:我希望使用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()
}
}
}