zipoutputstream 进行解压缩时winrar提示:不可预料的压缩文件末端

在做javaweb导出zip文件时,360压缩软件可以正常解压。但是winrar软件却报:不可预料的压缩文件末端 错误。在网上搜刮了许久,基本上解决方法是下以下两种:

一、输出流是否关闭,关闭顺序是否正确。先打开的后关闭。
二、是否调用ZipOutputStream的close()方法

closeEntry()方法是在putNextEntry()方法后调用。一般是在循环中使用。
最后需要调用close方法。
这两点。我排查了许久,仍然没有解决。
继续Google,发现博主zh521zh 写的一句话:

close方法必须在其他地方使用之前关闭

而我却是在ServletOutputStream 赋值之后才调用close方法。于是乎,方法提前,果真完美解决了问题!
启示:输出流不用之后及时关闭。

有效代码:

        response.reset(); // 非常重要
        FileInputStream fileInputStream = null;
        File returnFile = null;
        int pageSize=5000;
        String path= PropertiesFactory.getUploadProp().getProperty("localFileUrl");
   
			String absoZipPath = path+File.separator +".zip";
            FileOutputStream fo = new FileOutputStream(absoZipPath);
            ZipOutputStream zipout = new ZipOutputStream(fo);       
            byte[] buffer = new byte[1024];    
			int page = num/pageSize;
			for(int i=0;i<=page;i++){
				File returnFile = null;
				ZipEntry ze = new ZipEntry(returnFile.getName());
				zipout.putNextEntry(ze);
				FileInputStream fis = new FileInputStream(returnFile);
				int len=0;
				// 读入需要下载的文件的内容,打包到zip文件
				while ((len = fis.read(buffer, 0, buffer.length)) != -1) {
					zipout.write(buffer, 0, len);
				}
				zipout.flush();
				fis.close();
				zipout.closeEntry();
			}
			zipout.close();
            fo.close();//关键
			....
			ServletOutputStream out = null;
			String filename = "";
			Locale locale = request.getLocale();
			String userAgent = request.getHeader("user-agent");
			if (userAgent != null && userAgent.contains("Trident") && locale != null
					&& "zh".equalsIgnoreCase(locale.getLanguage()) && "CN".equalsIgnoreCase(locale.getCountry())) {
				filename = new String(returnFile.getName().getBytes("GB18030"), "ISO8859-1");
			} else {
				filename = new String(returnFile.getName().getBytes("UTF-8"), "ISO8859-1");
			}
			response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment; filename=" + filename);
			out = response.getOutputStream();
            IOUtils.copy(fileInputStream, out);
发布了137 篇原创文章 · 获赞 123 · 访问量 25万+

猜你喜欢

转载自blog.csdn.net/lz20120808/article/details/94020004
今日推荐