Merge multiple files to one Kotlin extension function

In my Android application i have a mechanism that i can download a file in many small parts and them merge them into one. So now i have downloaded the parts that are stored inside the LocalStorage below the folder Download/file_name. So that folder has inside (lets say) 30 files named by the sequence that they got created as segments (1,2,4,6,3,10,15,7,9,12,8....30)

I want to merge those files and append them into a single File and i want to write them by the correct sequence. First the 1, after the 2, after the 3 and so on...

Is there an elegant Kotlin extension function that could do such a job?


I don't think that exists exactly in the standard library. You could use something like this:

fun File.appendAll(bufferSize: Int = 4096, vararg files: File) {
    if (!exists()) {
        throw NoSuchFileException(this, null, "File doesn't exist.")
    }
    require(!isDirectory) { "The file is a directory." }
    FileOutputStream(this, true).use { output ->
        for (file in files) {
            if (file.isDirectory || !file.exists()) {
                continue // Might want to log or throw
            }
            file.forEachBlock(bufferSize) { buffer, bytesRead -> output.write(buffer, 0, bytesRead) }
        }
    }
}

First, you need to create the empty file you will append all these other files to.