将多个文件合并为一个 Kotlin 扩展函数

Merge multiple files to one Kotlin extension function

在我的 Android 应用程序中,我有一种机制可以将一个文件分成许多小部分,然后将它们合并为一个文件。 所以现在我已经下载了存储在文件夹 Download/file_name 下的 LocalStorage 中的部分。所以那个文件夹里面有(比方说)30个文件,这些文件按照它们被创建为片段的顺序命名(1,2,4,6,3,10,15,7,9,12,8....30)

我想合并这些文件并将它们附加到一个文件中,我想按正确的顺序写入它们。 首先是1,之后是2,之后是3等等...

有没有优雅的 Kotlin 扩展函数可以完成这样的工作?

我认为标准库中并不存在。你可以使用这样的东西:

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

首先,您需要创建一个空文件,您将向其中附加所有这些其他文件。