JavaWeb实现压缩多个文件并下载实例详解

时间:2021-10-26 06:28:51

下面一段代码给大家分享JavaWeb实现压缩多个文件并下载功能,具体代码如下所示:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
//文件名称
    String[] names={"one.jpg","two.jpg","three.jpg","four.jpg"};
    //四个文件流
    FileInputStream input1 = new FileInputStream(new File("文件路径"));
    FileInputStream input2 = new FileInputStream(new File("文件路径"));
    FileInputStream input3 = new FileInputStream(new File("文件路径"));
    FileInputStream input4 = new FileInputStream(new File("文件路径"));
    FileInputStream[] inputs={input1,input2,input3,input4};
    //ZIP打包图片
    File zipFile = new File("压缩文件存放路径");
    byte[] buf = new byte[1024];
    int len;
    ZipOutputStream zout=new ZipOutputStream(new FileOutputStream(zipFile));
    for (int i = 0; i < inputs.length; i++) {
      FileInputStream in =inputs[i];
      zout.putNextEntry(new ZipEntry(names[i])); 
      while ((len = in.read(buf)) > 0) {
        zout.write(buf, 0, len);
      }
      zout.closeEntry();
      in.close();
    }
    zout.close();
    //下载图片
    FileInputStream zipInput =new FileInputStream(zipFile);
    OutputStream out = response.getOutputStream();
    response.setContentType("application/octet-stream");
    response.setHeader("Content-Disposition", "attachment; filename=images.zip");
    while ((len=zipInput.read(buf))!= -1){
      out.write(buf,0,len);
    }
    zipInput.close();
    out.flush();
    out.close();
    //删除压缩包
    zipFile.delete();

总结

以上所述是小编给大家介绍的JavaWeb实现压缩多个文件并下载实例详解,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对服务器之家网站的支持!

原文链接:http://www.cnblogs.com/yzjSince92/p/6282869.html