java用zipOutputStream压缩后用WinRAR解压出现“不可预料的压缩文件末端”错误

问题解压文件出现“不可预料的压缩文件末端”错误,用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)排查流的关闭顺序是否正确,先打开的流,最后关闭。

  • 8
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 9
    评论
评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值