You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Kotlin服务中无需解压,按ZipEntry名称复制Zip条目至目标Zip文件

无需解压直接复制Zip条目到新Zip文件

完全可以通过Apache Compress实现这个需求,不需要将ZipEntry解压到本地磁盘,直接通过流的方式将条目内容复制到目标Zip文件中。

核心思路

  • 打开源Zip文件的输入流,遍历所有ZipEntry
  • 根据条目名称判断要写入的目标Zip文件(B或C)
  • 为目标Zip文件创建输出流,直接将源条目的输入流写入目标Zip的条目输出流,全程无需落地文件

Kotlin代码示例

import org.apache.commons.compress.archivers.zip.ZipArchiveEntry
import org.apache.commons.compress.archivers.zip.ZipArchiveInputStream
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream
import java.io.FileInputStream
import java.io.FileOutputStream

fun splitZipByEntryName(sourceZipPath: String, zipBPath: String, zipCPath: String) {
    // 初始化目标Zip输出流
    ZipArchiveOutputStream(FileOutputStream(zipBPath)).use { zipBOut ->
        ZipArchiveOutputStream(FileOutputStream(zipCPath)).use { zipCOut ->
            // 读取源Zip文件
            ZipArchiveInputStream(FileInputStream(sourceZipPath)).use { zipIn ->
                var entry: ZipArchiveEntry?
                while (zipIn.nextEntry.also { entry = it } != null) {
                    entry?.let { currentEntry ->
                        // 根据条目名称判断目标文件,这里示例以"prefixB-"开头的写入B,其余写入C
                        val targetOut = if (currentEntry.name.startsWith("prefixB-")) zipBOut else zipCOut
                        
                        // 创建新的Zip条目,复制原条目的属性(名称、压缩方法、时间等)
                        val newEntry = ZipArchiveEntry(currentEntry.name)
                        newEntry.method = currentEntry.method
                        newEntry.time = currentEntry.time
                        // 可按需复制其他属性,比如权限、注释等
                        
                        targetOut.putArchiveEntry(newEntry)
                        // 直接将源条目流复制到目标条目流
                        zipIn.copyTo(targetOut)
                        targetOut.closeArchiveEntry()
                    }
                }
            }
        }
    }
}

注意事项

  • 确保Apache Compress依赖已正确引入(比如Maven或Gradle)
  • 处理大文件时,这种流方式不会占用过多内存,性能更优
  • 可以根据实际需求调整条目名称的判断逻辑,比如正则匹配、后缀判断等

内容的提问来源于stack exchange,提问作者ollie

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 23:33:17