各位大虾,我现在是要把一些文本文件打包压缩后下载,测试后发现似乎文件个数多了以后会出现 closed connection的例外,自己定位在zf.closeEntry()上,
万望指教! 下面是完整的代码:
public static void creatZipFile(
HttpServletResponse response,
HttpServletRequest request,
List dataList,
boolean fileType,
String zipFileName)
throws FileUpDownException {
ServletOutputStream outputStream = null;
ZipOutputStream zf = null;
try {
outputStream = response.getOutputStream();

zf = new ZipOutputStream(outputStream);

zipFileName = new String(zipFileName.getBytes(), "ISO-8859-1");

response.setContentType("application/zip");   response.setHeader("Pragma", "private");
response.setHeader("Cache-Control", "max-age=0");
response.setHeader("Content-Disposition","attachment;filename=" + zipFileName); zf.setLevel(Deflater.BEST_COMPRESSION);
for (int i = 0; i < dataList.size(); i++) {
Map fileList = (Map)dataList.get(i);
String fileName = (String)fileList.get("FileName");
ZipEntry entry = new ZipEntry(fileName);
entry.setTime(System.currentTimeMillis());
zf.putNextEntry(entry);
if (fileList.get("TempletFilePath") == null) {
List colList = null;
if (fileList.get("ColumList") != null) {
colList = (List)fileList.get("ColumList");
}
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
List fileDataList = (List)fileList.get("FileDataList");
outputBasicData(
colList,
fileDataList,
new PrintStream(buffer));

zf.write(buffer.toByteArray());
zf.closeEntry();
} else {
String templetFilePath =
(String)fileList.get("TempletFilePath");
File file = new File(templetFilePath + "\\" + fileName);
if (file.exists()) {
FileInputStream fileIn = new FileInputStream(file);
byte[] buffer = new byte[4096];
while (fileIn.read(buffer) != -1) {
zf.write(buffer);
}
zf.closeEntry();
fileIn.close();
}
} }
zf.flush();
zf.close();
} catch (IOException e) {
throw new FileUpDownException(e);
} finally {
try {
if (outputStream != null) {
outputStream.close();
}
if (zf != null) {
zf.close();
}
} catch (IOException e1) {
// do nothing
}
} }

解决方案 »

  1.   

    各位是不是看着代码太多阿?主要的就是: ByteArrayOutputStream buffer = new ByteArrayOutputStream();
    List fileDataList = (List)fileList.get("FileDataList");
    outputBasicData(colList,fileDataList,new PrintStream(buffer));
                      zf.write(buffer.toByteArray());
    zf.closeEntry();
    这些代码在for循环里面,为什么前几次zf.closeEntry()都OK,后来就出exception了呢
      

  2.   

    在你的程序里zf.closeEntry();
    执行两次
    在if里面就不要写这句了
      

  3.   

    楼上的兄台,if里面的zf.closeEntry();去掉后还是一样啊,压缩到第10个文件时就报exception了