问题解压文件出现“不可预料的压缩文件末端”错误,用360解压和快压解压没有问题,用WinRAR解压出错
后台代码压缩方法
/**
* 递归压缩文件夹
* @param srcRootDir 压缩文件夹根目录的子路径
* @param file 当前递归压缩的文件或目录对象
* @param zos 压缩文件存储对象
* @throws Exception
*/
public static void zip(String srcRootDir, File file, ZipOutputStream zos) throws Exception{
if (file == null) {
return;
}
String subPath = file.getAbsolutePath();
int index = subPath.indexOf(srcRootDir);
if (index != -1) {
subPath = subPath.substring(srcRootDir.length());
}
//如果是文件,则直接压缩该文件
if (file.isFile()) {
int count, bufferLen = 1024;
byte data[] = new byte[bufferLen];//获取文件相对于压缩文件夹根目录的子路径
zos.putNextEntry(new ZipEntry(subPath));
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
while ((count = bis.read(data, 0, bufferLen)) != -1) {
zos.write(data, 0, count);
}
bis.close();
zos.closeEntry();
}else {
//压缩目录中的文件或子目录
File[] childFiles = file.listFiles();
if(childFiles.length==0){
zos.putNextEntry(new ZipEntry(subPath+"/"));
}else{
for (int n=0; n<childFiles.length; n++) {
childFiles[n].getAbsolutePath().indexOf(file.getAbsolutePath());
zip(srcRootDir, childFiles[n], zos);
}
}
}
}
调用zipUtil.zip方法
ZipOutputStream out = new ZipOutputStream(fileOutStream);
ZipUtil.zip(infile.getAbsolutePath() , infile, out);
out.close();//之前只关闭out.closeEntry() 并没有将out流关闭
fileOutStream.close();
ZipOutStream 最开始调用closeEntry()去关闭流,以为跟close(方法一样,导致了解压文件出错。流关闭一定要用close(),closeEntry()关闭是针对往压缩文件写入实体,之后在调用closeEntry(),这两个有这很大的区别。
总结下
(1)出现解压出错,可以先排查是否流没有进行关闭
(2)排查流的关闭顺序是否正确,先打开的流,最后关闭。