我有一大堆从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
fun File.copyInputStreamToFile(inputStream: InputStream) {
inputStream.use { input ->
this.outputStream().use { fileOut ->
input.copyTo(fileOut)
}
}
}
Run Code Online (Sandbox Code Playgroud)
小智 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)
| 归档时间: |
|
| 查看次数: |
13429 次 |
| 最近记录: |