如何用SevenZFile类正确解压.7z文件?遇数组越界异常
使用SevenZFile正确解压7z归档文件的方法
错误原因分析
你遇到的ArrayIndexOutOfBoundsException大概率是因为没按正确逻辑遍历归档条目,或是处理流时未遵循逐个条目处理的规则。SevenZFile要求必须逐个遍历并处理每个归档条目,不能直接批量读取所有内容。
正确使用步骤
- 打开
SevenZFile实例,指向已复制到外部目录的7z文件 - 循环遍历每个
SevenZArchiveEntry:- 判断当前条目是否为目录,若是则创建对应目录
- 若为文件则创建输出流,通过
IOUtils.copy将条目内容写入目标文件
- 处理完每个条目后,关闭对应的输入/输出流
- 最终关闭
SevenZFile实例
完整代码示例
import org.apache.commons.compress.archivers.sevenz.SevenZArchiveEntry; import org.apache.commons.compress.archivers.sevenz.SevenZFile; import org.apache.commons.io.IOUtils; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; public class SevenZExtractor { public static void extract7z(File sevenZFile, String destDir) throws IOException { // 创建目标根目录 File destinationDir = new File(destDir); if (!destinationDir.exists()) { destinationDir.mkdirs(); } // 自动关闭SevenZFile资源 try (SevenZFile zFile = new SevenZFile(sevenZFile)) { SevenZArchiveEntry entry; // 逐个遍历所有归档条目,直到返回null表示遍历结束 while ((entry = zFile.getNextEntry()) != null) { // 跳过无效空条目 if (!entry.isDirectory() && entry.getSize() <= 0) { continue; } File targetFile = new File(destinationDir, entry.getName()); if (entry.isDirectory()) { // 创建条目对应的目录 targetFile.mkdirs(); } else { // 确保文件的父目录存在 File parentDir = targetFile.getParentFile(); if (!parentDir.exists()) { parentDir.mkdirs(); } // 复制当前条目内容到目标文件,自动关闭输出流 try (FileOutputStream outputStream = new FileOutputStream(targetFile)) { IOUtils.copy(zFile.getInputStream(entry), outputStream); } } } } } }
关键注意事项
- 必须用
zFile.getNextEntry()循环获取条目,直到返回null,这是SevenZFile的标准遍历方式 - 处理文件时要先确保父目录存在,避免因目录缺失导致写入失败
- 所有流资源通过try-with-resources自动关闭,防止资源泄漏
- 绝对不能尝试一次性读取所有条目内容,必须逐个处理每个文件条目
内容的提问来源于stack exchange,提问作者Louis Chabert
相关产品推荐
相关产品推荐

