import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.Date; import java.util.zip.CRC32; import java.util.zip.CheckedOutputStream; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import java.util.zip.ZipOutputStream; /** * zip压缩文件的工具类 * * @author lxp * */ public final class ZipUtil { private static final int BUFFER = 8192; /** * 把一组文件压缩成一个zip包 * * @param deleteSrcFile * 压缩后是否删除源文件 * @param decFile * 目标文件,如data.zip * @param srcFile * n个源文件 * @throws IOException */ public static void compressFile(boolean deleteSrcFile, String decFile, String... srcFile) throws IOException { ZipOutputStream out = null; try { if (decFile == null || decFile == "") { throw new IllegalArgumentException("decFile 不能为空"); } File descFile = new File(decFile); FileOutputStream fileOutputStream = new FileOutputStream(descFile); CheckedOutputStream cos = new CheckedOutputStream(fileOutputStream, new CRC32()); out = new ZipOutputStream(cos); for (String f : srcFile) { File file = new File(f); if (file.exists()) { BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file)); ZipEntry entry = new ZipEntry(file.getName()); out.putNextEntry(entry); int count; byte data[] = new byte[BUFFER]; while ((count = bis.read(data, 0, BUFFER)) != -1) { out.write(data, 0, count); } bis.close(); if (deleteSrcFile) { file.delete(); } } } out.close(); descFile.setLastModified(new Date().getTime()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); if(out != null){ out.close(); } throw e; } } /** * 解压zip * @param zipfile zip文件路径 * @param extdir 解压目录 */ public static void unzipFile(String zipfile,String extdir){ File f = new File(zipfile); if(null==extdir){ extdir=f.getParent(); } File ext = new File(extdir); if(!ext.exists()){ ext.mkdirs(); } try { FileInputStream fi = new FileInputStream(f); ZipInputStream zipInput = new ZipInputStream(fi); ZipEntry zip = zipInput.getNextEntry(); while(zip!=null){ File fo = new File(extdir+zip.getName()); makedirs(fo); FileOutputStream fout = new FileOutputStream(fo); byte inbuf[] = new byte[BUFFER]; int n = 0; while ( (n = zipInput.read(inbuf, 0, BUFFER)) != -1) { fout.write(inbuf, 0, n); } fout.close(); zip = zipInput.getNextEntry(); } zipInput.close(); fi.close(); } catch (Exception e) { e.printStackTrace(); } } private static void makedirs(File f){ File ff = new File(f.getParent()); System.out.println(f.getParent()); if(!ff.exists())ff.mkdirs(); } }