项目需求,解压zip文件,我使用的是 java.util.zip
的 ZipFile
。
贴个好用的解压代码:
File toFile = new File("D:\\data\\000001\\pbsFile\\test.zip");
ZipFile zipFile = new ZipFile(toFile, Charset.forName("GBK"));
Enumeration<?> entries = zipFile.entries();
while (entries.hasMoreElements()) {
ZipEntry entry = (ZipEntry) entries.nextElement();
String zipName = entry.getName();
InputStream in = zipFile.getInputStream(entry);
// 这里是解压后的输出路径
String outpath = ("D:\\data\\000001\\pbsFile/"+zipName).replace("/", File.separator);
File file2 = new File(outpath.substring(0,outpath.lastIndexOf(File.separator)));
if (!file2.exists()) {
file2.mkdirs();
}
File outPathFile = new File(outpath);
//文件夹就不解压;
if (outPathFile.isDirectory()) {
continue;
}
OutputStream out = new FileOutputStream(outpath);
byte[] bf = new byte[2048];
int len;
while ((len = in.read(bf)) > 0) {
out.write(bf, 0, len);
}
in.close();
out.close();
}
zipFile.close();
1. java.lang.IllegalArgumentException: MALFORMED
的异常解决办法
在创建 ZipFile 对象时,后面加上 GBK
ZipFile zipFile = new ZipFile(toFile, Charset.forName("GBK"));
2. error in opening zip file
的异常解决
我出现异常的地方同样时在实例化 ZipFile 时,后来多次测试发现,在我压缩文件的时候,会有不同的压缩算法,其中算法为LZMA2:21
的压缩文件在实例化时会报error,而Deflate
和Store
可以正常解压。
看了一下ZipFile的源码,关于压缩方法只定义了STORED和DEFLATED,推测可能是因为这个原因导致解压失败。
解决办法:使用windows的压缩文件或者用其他解压工具的时候注意一下压缩方法。