JAVA将多个文件打包成ZIP压缩包输出

工具类一(将多个远端文件读取并压缩)

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletResponse;

public class ZipUtil {
	/**
	 * 压缩文件
	 * @param files 键值对-》(文件名:文件链接)
	 * @param outputStream
	 * @throws Exception 
	 * @throws IOException
	 */
	public static void zipPersonPhotoFile(Map<String,String> files, ZipOutputStream outputStream) {
	    try {
	    	Set<Entry<String, String>> entrySet = files.entrySet();
	        for (Entry<String, String> file:entrySet) {
	            try {
	                zipFile(getImgIs(file.getValue()),file.getKey(), outputStream);
	            } catch (Exception e) {
	                continue;
	            }
	        }
	    } catch (Exception e) {
	        e.printStackTrace();
	    } finally {
	    	try {
				outputStream.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} 
	    }
	}

	/**
	 * 将文件写入到zip文件中
	 * @param inputFile
	 * @param outputstream
	 * @throws Exception
	 */
	public static void zipFile(InputStream is, String fileName, ZipOutputStream outputstream) throws IOException, ServletException {
	    try {
	        if (is != null) {
                BufferedInputStream bInStream = new BufferedInputStream(is);
                ZipEntry entry = new ZipEntry(fileName);
                outputstream.putNextEntry(entry);
                int len = 0 ;
                byte[] buffer = new byte[10 * 1024];
                while ((len = is.read(buffer)) > 0) {
                	outputstream.write(buffer, 0, len);
                	outputstream.flush();
                }
                outputstream.closeEntry();//Closes the current ZIP entry and positions the stream for writing the next entry
                bInStream.close();//关闭
                is.close();
	        } else {
	            throw new ServletException("文件不存在!");
	        } 
	    } catch (IOException e) {
	        throw e;
	    }
	}
	
    /**
    * 获取文件流
    */
	public static InputStream getImgIs(String imgURL) throws IOException{
		//new一个URL对象
		URL url = new URL(imgURL);
		//打开链接  
        HttpURLConnection conn = (HttpURLConnection)url.openConnection();  
        //设置请求方式为"GET"  
        conn.setRequestMethod("GET");
        //超时响应时间为5秒  
        conn.setConnectTimeout(5 * 1000);  
        //通过输入流获取图片数据  
        return conn.getInputStream();
	}

	/**
	 * 下载打包的文件
	 *
	 * @param file
	 * @param response
	 */
	public static void downloadZip(File file, HttpServletResponse response) {
	    try {
	        // 以流的形式下载文件。
	        BufferedInputStream fis = new BufferedInputStream(new FileInputStream(file.getPath()));
	        byte[] buffer = new byte[fis.available()];
	        fis.read(buffer);
	        fis.close();
	        // 清空response
	        response.reset();
	        OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
	        response.setCharacterEncoding("UTF-8");
	        response.setContentType("application/octet-stream");
	        response.setHeader("Content-Disposition", "attachment;filename=" + file.getName());
	        toClient.write(buffer);
	        toClient.flush();
	        toClient.close();
	        file.delete();
	    } catch (IOException ex) {
	        ex.printStackTrace();
	    }
	}

}

实例 

public void zipFile (Map<String,String> map) {
		try {
			ZipUtil.zipPersonPhotoFile(map, new ZipOutputStream(new FileOutputStream(new File(zipFilePath))));
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
}

工具类二(将本地某个文件/文件夹压缩)

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import javax.servlet.ServletException;

import org.apache.commons.io.FileUtils;

public class ZipUtils {

  private ZipUtils() {
    throw new IllegalStateException("Utility class");
  }

  /**
   * 将文件/目录进行压缩
   * @param sourceFile 原文件/目录
   * @param targetZipFile 压缩后目标文件
   * @throws IOException 
   */
  public static void zipFiles(File sourceFile, File targetZipFile) throws IOException {
    ZipOutputStream outputStream = null;
    try {
      outputStream = new ZipOutputStream(new FileOutputStream(targetZipFile));
      addEntry("", sourceFile, outputStream);
    } catch (Exception e) {
      throw new IOException(e);
    } finally {
      outputStream.close();
    }
  }

  /**
   * 将文件写入到zip文件中
   * @param source
   * @param outputstream
   * @throws IOException
   * @throws ServletException
   */
  private static void addEntry(String base, File source, ZipOutputStream outputstream)
      throws IOException, ServletException {
    FileInputStream is = null;
    try {
      String entry = base + source.getName();
      if (source.isDirectory()) {
        for (File file : source.listFiles()) {
          // 递归导入文件
          addEntry(entry + File.separator, file, outputstream);
        }
      } else {

        is = FileUtils.openInputStream(source);
        if (is != null) {
          outputstream.putNextEntry(new ZipEntry(entry));

          int len = 0;
          byte[] buffer = new byte[10 * 1024];
          while ((len = is.read(buffer)) > 0) {
            outputstream.write(buffer, 0, len);
            outputstream.flush();
          }
          outputstream.closeEntry();
        }
      }

    } catch (IOException e) {
      throw e;
    } finally {
      if (is != null) {
        is.close();
      }
    }

  }

}

 

  • 2
    点赞
  • 37
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值