如何在android中压缩目录?

时间:2020-10-16 16:05:11

标签: android kotlin

我需要将文件夹备份设置为zip文件。我尝试了此类:

class ZipFunctions(val context: Context) {

fun zip(files: ArrayList<String>, zipFileName: String?) {
    try {
        val fileOutPut =
            context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)?.path + "/$zipFileName"
        var origin: BufferedInputStream?
        val dest = FileOutputStream(fileOutPut)
        val out = ZipOutputStream(
            BufferedOutputStream(
                dest
            )
        )
        val data = ByteArray(2048)
        for (i in files.indices) {
            val fi = FileInputStream(files[i])
            origin = BufferedInputStream(fi, 2048)
            val entry = ZipEntry(files[i].substring(files[i].lastIndexOf("/") + 1))
            out.putNextEntry(entry)
            var count: Int
            while (origin.read(data, 0, 2048).also { count = it } != -1) {
                out.write(data, 0, count)
            }
            origin.close()
        }
        out.close()
    } catch (e: Exception) {
        e.printStackTrace()
    }
}
}

并以此方式使用它:

    val files = ArrayList<String>()
    val name1 = this.getDir(
        "files",
        MODE_PRIVATE
    ).path
    val name2 = this.getDir(
        "image",
        MODE_PRIVATE
    ).path
    files.add(name1)
    files.add(name2)
    val zipFunctions = ZipFunctions(this)
    zipFunctions.zip(files, "zip_file.zip")

但是它将创建一个空的zip文件。应用内日志,我看到以下行:

W / System.err:java.io.FileNotFoundException:/ data / user / 0 / app_package_name / app_image:打开失败:EISDIR(是目录)。

你能帮我吗?

0 个答案:

没有答案