问题描述
- java 实现生成txt压缩后返回客户端,不知道哪错了。生成的压缩文件都是损坏的
-
try {
OutputStream os = res.getOutputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ZipOutputStream zipOut = new ZipOutputStream(baos);
ZipEntry entry = new ZipEntry("goods.txt");
zipOut.putNextEntry(entry);
zipOut.write(bytes, 0, bytes.length);res.reset(); res.setContentType("application/OCTET-STREAM;charset=GBK"); res.setHeader("pragma", "no-cache"); res.addHeader("Content-Disposition", "attachment;filename=goods.zip"); os.write(baos.toByteArray(), 0, baos.toByteArray().length); zipOut.flush(); zipOut.closeEntry(); baos.close(); zipOut.close(); os.close(); } catch (Exception e) { logger.error(e,e); }
解决方案
请参看,希望对你有用
http://snowolf.iteye.com/blog/644591
解决方案二:
在os.close();之前添加os.flush();试一下呢
解决方案三:
有谁遇到过这种问题吗?
解决方案四:
不要沉了,有人会吗?
解决方案五:
我感觉是不是你的关闭顺序有问题啊。
FileOutputStream f=new FileOutputStream("text.zip");
CheckedOutputStream csum=new CheckedOutputStream(f,new Adler32());
ZipOutputStream zos=new ZipOutputStream(csum);
BufferedOutputStream out = new BufferedOutputStream(zos);
zos.setComment("A test of Java Ziping!");
BufferedReader in =new BufferedReader(new FileReader("123.txt"));
zos.putNextEntry(new ZipEntry("123.txt"));
int c;
while((c = in.read()) != -1){
out.write(c);
}
in.close();
out.flush();
out.close();
}
解决方案六:
问题已解决:
/**
* 压缩数据返回客户端
* @param req
* @param res
* @param bytes
* @throws Exception
*/
public static void zip(HttpServletRequest req, HttpServletResponse res,byte[] bytes) throws Exception {
ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
compress(bais, baos);
OutputStream os = res.getOutputStream();
res.reset();
res.setContentType("application/zip");
res.setHeader("pragma", "no-cache");
res.addHeader("Content-Disposition", "attachment;filename=goods.zip");
byte[] output = baos.toByteArray();
os.write(output, 0, output.length);
baos.flush();
baos.close();
bais.close();
os.close();
}
/**
* 数据压缩
*
* @param is
* @param os
* @throws Exception
*/
public static void compress(InputStream is, OutputStream os)
throws Exception {
ZipOutputStream zipOut = new ZipOutputStream(os);
ZipEntry entry = new ZipEntry("goods.txt");
zipOut.putNextEntry(entry);
int count;
byte data[] = new byte[2048*2];
while ((count = is.read(data, 0, data.length)) != -1) {
zipOut.write(data, 0, count);
}
zipOut.closeEntry();
zipOut.finish();
zipOut.flush();
zipOut.close();
}