在Kotlin中写入一个大的InputStream文件

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

我写了下面的功能扩展工程。 但我不禁想到有一个更干净的方式来做到这一点。

注意 :我希望使用资源尝试自动关闭流和文件

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函数来简化你的函数 :

 fun File.copyInputStreamToFile(inputStream: InputStream) { inputStream.use { input -> this.outputStream().use { fileOut -> input.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") 

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