欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2023-12-20 08:07:10
下面一段代码给大家分享javaweb实现压缩多个文件并下载功能,具体代码如下所示: //文件名称 string[] names={"one.jpg","...

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

//文件名称
    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实现压缩多个文件并下载实例详解,希望对大家有所帮助

上一篇:

下一篇: