Jeff Campbell
Jeff Campbell

Reputation: 1635

Write a large Inputstream to File in Kotlin

I have a large stream of text coming back from REST web service and I would like to write it directly to file. What is the simplest way of doing this?

I have written the following function extension that WORKS. But I can't help thinking that there is a cleaner way of doing this.

Note: I was hoping to use try with resources to auto close the stream and file

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()
        }
    }
}

Upvotes: 48

Views: 39079

Answers (5)

hackall360
hackall360

Reputation: 27

What appears to have worked for me is this:

fun fileCopyer(localFileA: File, localFileB: File) {
var output = localFileA.inputStream()
output.copyTo(localFileB.outputStream())
output.close()
}

Upvotes: -1

yole
yole

Reputation: 97268

You can simplify your function by using the copyTo function:

fun File.copyInputStreamToFile(inputStream: InputStream) {
    this.outputStream().use { fileOut ->
        inputStream.copyTo(fileOut)
    }
}

Upvotes: 106

romiope
romiope

Reputation: 786

My proposition is:

fun InputStream.toFile(path: String) {
    File(path).outputStream().use { this.copyTo(it) }
}

without closing current stream

InputStream.toFile("/path/filename")

also, do not forget to handle exceptions, for example if write permission is denied :)

Upvotes: 17

Sumit Pansuriya
Sumit Pansuriya

Reputation: 553

You needs to do like this

@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()
}

Upvotes: 0

romiope
romiope

Reputation: 786

I suggest to make like this:

fun InputStream.toFile(path: String) {
    use { input ->
        File(path).outputStream().use { input.copyTo(it) }
    }
}

and then to use like:

InputStream.toFile("/some_path_to_file")

Upvotes: 10

Related Questions