Java导出zip文件
前些日子,需要使用Java来实现导出zip文件。这两天刚好没事儿,简单的整理了一下,共享给大家,也以备将来自己忘记。
当然,Java web项目一般是遵循这mvc模式,那就简单的从action上入手介绍:
action中主要是输出到客户端。
其中的方法大致如下:
1 public String exportXml(){
2 try {
3 response.setContentType("application/zip;charset=UTF-8");
4 response.setHeader("Cache-Control", "no-cache");
5 Calendar calendar = iExportXMLService.selectSystemDate();
6 StringBuffer stringBuffer = new StringBuffer();
7 if(calendar != null){
8 stringBuffer.append(calendar.get(Calendar.YEAR));
9 stringBuffer.append("-");
10 stringBuffer.append((calendar.get(Calendar.MONTH)+1));
11 stringBuffer.append("-");
12 stringBuffer.append(calendar.get(Calendar.DATE));
13 stringBuffer.append("_");
14 stringBuffer.append(Producer.generateIdOfTen());
15 stringBuffer.append(".zip");
16 fileName = stringBuffer.toString();
17 }else {
18 stringBuffer.append("exportXML_");
19 stringBuffer.append(Producer.generateIdOfTen());
20 stringBuffer.append(".zip");
21 }
22 fileName = new String(fileName.getBytes(), "ISO8859-1");
23 response.addHeader("Content-Disposition","attachment;filename=\"" + fileName + "\"");
24 ServletOutputStream out = response.getOutputStream();
25 if(archiveNumbers!=null&&!archiveNumbers.equals("")){
26 iExportXMLService.exportArchiveXMLByArchiveNumbers(archiveNumbers,fileName,""+session.get("tempFolder")+File.separator+"xml");
27 }else{
28 out.flush();
29 out.close();
30 return null;
31 }
32 out.write(FileUtil.getBytesFromFile(new File(""+session.get("tempFolder")+File.separator+"xml"+File.separator+fileName)));
33 out.flush();
34 out.close();
35 } catch (Exception e) {
36 e.printStackTrace();
37 session.put("exceptionInfoClass", e);
38 return "exceptionOperateAction";
39 }
40 return null;
41 }
然后是service层生成zip文件到tempFolder临时文件夹下(核心的技术代码如下):
byte[] buffer = new byte[1024];
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(tempFolder+File.separator+fileName));
//需要打包的zipfiles数组
List<File> files = new ArrayList<File>();
//通过相应的业务来封装自己的list。
FileInputStream fis = null;
for (File eachFile : allFiles) {
fis = new FileInputStream(eachFile);
out.putNextEntry(new ZipEntry(eachFile.getName()));
int len;
while ((len = fis.read(buffer)) > 0) {
out.write(buffer, 0, len);
}
out.closeEntry();
fis.close();
}
out.close();
嗯,生成文件,大致如上了。嗯,还存在一个小问题就是,主要是在服务器端会生成相应的zip包,占用硬盘。
摘自 Moving
补充:软件开发 , Java ,