本博客是自己在学习和工作途中的积累与总结,仅供自己参考,也欢迎大家转载,转载时请注明出处。
http://www.cnblogs.com/king-xg/p/6424788.html
上代码:
package com.king.util; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; /** * 压缩文件工具类 * 功能: 支持单文件下载,多文件下载,一目录多文件下载,一目录一文件下载 * * @author xg君 * */ public class CompressFileUtil { private final static byte[] bytes = new byte[1024]; /** * 单文件压缩 * * @param srcFilePath * @param descFilePath * @param directory * @throws Exception */ public static void compress(String srcFilePath, String descFilePath, String directory) throws Exception{ // 源文件 File srcFile = new File(srcFilePath); // 目标文件 File descFile = new File(descFilePath); ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(descFile)); compress(srcFile,zos,directory); zos.close(); } private static void compress(File srcFile ,ZipOutputStream zos, String directory) throws Exception{ BufferedInputStream bis = new BufferedInputStream(new FileInputStream(srcFile));
String basePath = "";
if (directory.trim().length() != 0) {
basePath = directory + File.separator;
}
zos.putNextEntry(new ZipEntry(basePath + srcFile.getName())); int len = -1; while((len = bis.read(bytes)) > 0){ zos.write(bytes); } zos.flush(); bis.close(); } /** * 多文件下载 - one or no directory * * @param srcFiles * @param descFilePath * @throws Exception */ public static void compress(File[] srcFiles, String descFilePath, String directory) throws Exception{ ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(new File(descFilePath))); for(File file : srcFiles){ compress(file,zos,directory); } zos.close(); } /** * 多文件下载 - multiple files and directories * * @param srcFiles * @param descFilePath * @param directories * @throws Exception */ public static void compress(File[] srcFiles, String descFilePath, String[] directories) throws Exception{ if(srcFiles.length != directories.length){ throw new Exception("源文件(srcFiles)数量与目录(directories)数量不符!"); } ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(new File(descFilePath))); for(int i = 0; i < srcFiles.length; i++){ compress(srcFiles[i], zos, directories[i]); } zos.close(); } /** * 多文件下载 - one directory for multiple files * * @param map * @param descFilePath * @throws Exception */ public static void compress(Map<String, String[]> map, String descFilePath) throws Exception{ ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(new File(descFilePath))); Set<Entry<String, String[]>> set = map.entrySet(); for(Entry<String, String[]> en : set){ String directory = en.getKey(); String[] srcFilesPath = en.getValue(); for(String srcFilePath : srcFilesPath){ compress(new File(srcFilePath),zos,directory); } } zos.close(); } }
这是我在工作之余,小结的代码。