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

从ZipInputStream中逐个提取文件至指定磁盘位置

解决ZipInputStream提取文件到磁盘的问题

你当前的代码只创建了空文件,没把压缩包内的文件内容写入进去。getExtras()是用来获取ZipEntry的额外扩展数据,和文件本身的内容无关,要提取文件内容,直接通过ZipInputStream的read()方法读取即可。

另外还要注意处理目录的情况——如果ZipEntry是目录,需要先创建对应的目录;如果是文件,要确保其父目录存在,否则写入会报错。

修改后的完整代码如下:

try {
    ZipInputStream zipInputStream = new ZipInputStream(zip.getBody().getInputStream());
    ZipEntry temp;
    // 指定提取到的根目录,比如当前目录下的extracted文件夹
    String extractRoot = "extracted";
    File rootDir = new File(extractRoot);
    if (!rootDir.exists()) {
        rootDir.mkdirs();
    }

    while ((temp = zipInputStream.getNextEntry()) != null) {
        // 拼接完整的输出路径
        File outputFile = new File(rootDir, temp.getName());
        
        if (temp.isDirectory()) {
            // 如果是目录,创建目录
            outputFile.mkdirs();
        } else {
            // 确保父目录存在
            File parentDir = outputFile.getParentFile();
            if (!parentDir.exists()) {
                parentDir.mkdirs();
            }
            // 读取压缩包内的文件内容并写入到磁盘文件
            try (FileOutputStream outputStream = new FileOutputStream(outputFile)) {
                byte[] buffer = new byte[1024 * 4]; // 4KB缓冲区,提升读写效率
                int len;
                while ((len = zipInputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, len);
                }
                System.out.println("已提取文件: " + temp.getName());
            }
        }
        // 关闭当前ZipEntry
        zipInputStream.closeEntry();
    }
} catch (IOException e) {
    e.printStackTrace();
}

关键说明:

  • 新增了提取根目录的设置,避免文件直接提取到当前目录造成混乱
  • 处理了目录类型的ZipEntry,递归创建所需目录
  • 使用缓冲区进行读写,比单字节读写效率更高
  • 显式调用closeEntry()关闭当前条目,释放资源

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 07:45:20