在 Kotlin 中将大型输入流写入文件
Write a large Inputstream to File in Kotlin
我有大量文本从 REST Web 服务返回,我想将其直接写入文件。最简单的方法是什么?
我编写了以下有效的功能扩展。但我不禁想到有一种更简洁的方法可以做到这一点。
注意:我希望使用 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()
}
}
}
您可以使用 copyTo function:
来简化您的函数
fun File.copyInputStreamToFile(inputStream: InputStream) {
this.outputStream().use { fileOut ->
inputStream.copyTo(fileOut)
}
}
我建议这样制作:
fun InputStream.toFile(path: String) {
use { input ->
File(path).outputStream().use { input.copyTo(it) }
}
}
然后像这样使用:
InputStream.toFile("/some_path_to_file")
你需要这样做
@Throws
fun copyDataBase() {
var myInput = context.getAssets().open(DB_NAME)
var outFileName = DB_PATH + DB_NAME
var fileOut: OutputStream = FileOutputStream(outFileName)
val buffer: ByteArray = ByteArray(1024)
var length: Int? = 0
while (true) {
length = myInput.read(buffer)
if (length <= 0)
break
fileOut.write(buffer, 0, length)
}
fileOut.flush()
fileOut.close()
myInput.close()
throw IOException()
}
我的提议是:
fun InputStream.toFile(path: String) {
File(path).outputStream().use { this.copyTo(it) }
}
不关闭当前流
InputStream.toFile("/path/filename")
另外,不要忘记处理异常,例如写权限被拒绝:)
似乎对我有用的是:
fun fileCopyer(localFileA: File, localFileB: File) {
var output = localFileA.inputStream()
output.copyTo(localFileB.outputStream())
output.close()
}
我有大量文本从 REST Web 服务返回,我想将其直接写入文件。最简单的方法是什么?
我编写了以下有效的功能扩展。但我不禁想到有一种更简洁的方法可以做到这一点。
注意:我希望使用 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()
}
}
}
您可以使用 copyTo function:
来简化您的函数fun File.copyInputStreamToFile(inputStream: InputStream) {
this.outputStream().use { fileOut ->
inputStream.copyTo(fileOut)
}
}
我建议这样制作:
fun InputStream.toFile(path: String) {
use { input ->
File(path).outputStream().use { input.copyTo(it) }
}
}
然后像这样使用:
InputStream.toFile("/some_path_to_file")
你需要这样做
@Throws
fun copyDataBase() {
var myInput = context.getAssets().open(DB_NAME)
var outFileName = DB_PATH + DB_NAME
var fileOut: OutputStream = FileOutputStream(outFileName)
val buffer: ByteArray = ByteArray(1024)
var length: Int? = 0
while (true) {
length = myInput.read(buffer)
if (length <= 0)
break
fileOut.write(buffer, 0, length)
}
fileOut.flush()
fileOut.close()
myInput.close()
throw IOException()
}
我的提议是:
fun InputStream.toFile(path: String) {
File(path).outputStream().use { this.copyTo(it) }
}
不关闭当前流
InputStream.toFile("/path/filename")
另外,不要忘记处理异常,例如写权限被拒绝:)
似乎对我有用的是:
fun fileCopyer(localFileA: File, localFileB: File) {
var output = localFileA.inputStream()
output.copyTo(localFileB.outputStream())
output.close()
}