压缩工具类 - ZipUtils.java

压缩工具类,提供压缩文件、解压文件的方法。

 

源码如下:(点击下载 - ZipUtils.java 、FolderUtils.javaant-1.7.0.jarcommons-io-2.4.jarcommons-lang-2.6.jar)

  1 import java.io.BufferedInputStream;
  2 import java.io.BufferedOutputStream;
  3 import java.io.File;
  4 import java.io.FileInputStream;
  5 import java.io.FileOutputStream;
  6 import java.io.IOException;
  7 import java.io.InputStream;
  8 import java.util.Enumeration;
  9 import org.apache.commons.io.FilenameUtils;
 10 import org.apache.commons.io.IOUtils;
 11 import org.apache.commons.lang.ArrayUtils;
 12 import org.apache.commons.lang.StringUtils;
 13 import org.apache.tools.zip.ZipEntry;
 14 import org.apache.tools.zip.ZipFile;
 15 import org.apache.tools.zip.ZipOutputStream;
 16 
 17 /**
 18  * 压缩工具类
 19  * 
 20  */
 21 public class ZipUtils {
 22 
 23     private static final String DEFAULT_CHARSET = "UTF-8";
 24 
 25     /**
 26      * 压缩文件夹
 27      *
 28      * @param zipFileName
 29      *            打包后文件的名称,含路径
 30      * @param sourceFolder
 31      *            需要打包的文件夹或者文件的路径
 32      * @param zipPathName
 33      *            打包目的文件夹名,为空则表示直接打包到根
 34      */
 35     public static void zip(String zipFileName, String sourceFolder, String zipPathName) throws Exception {
 36         ZipOutputStream out = null;
 37         try {
 38             File zipFile = new File(zipFileName);
 39 
 40             FolderUtils.mkdirs(zipFile.getParent());
 41             out = new ZipOutputStream(zipFile);
 42             out.setEncoding(DEFAULT_CHARSET);
 43             if (StringUtils.isNotBlank(zipPathName)) {
 44                 zipPathName = FilenameUtils.normalizeNoEndSeparator(zipPathName, true) + "/";
 45             } else {
 46                 zipPathName = "";
 47             }
 48             zip(out, sourceFolder, zipPathName);
 49         } catch (IOException e) {
 50             e.printStackTrace();
 51             throw new Exception(e);
 52         } finally {
 53             IOUtils.closeQuietly(out);
 54         }
 55     }
 56 
 57     /**
 58      * 压缩文件夹
 59      *
 60      * @param zipFile
 61      *            a {@link java.lang.String} object.
 62      * @param source
 63      *            a {@link java.lang.String} object.
 64      */
 65     public static void zip(String zipFile, String source) throws Exception {
 66         File file = new File(source);
 67         zip(zipFile, source, file.isFile() ? StringUtils.EMPTY : file.getName());
 68     }
 69 
 70     /**
 71      * 压缩文件夹
 72      *
 73      * @param zipFile
 74      *            a {@link java.io.File} object.
 75      * @param source
 76      *            a {@link java.io.File} object.
 77      */
 78     public static void zip(File zipFile, File source) throws Exception {
 79         zip(zipFile.getAbsolutePath(), source.getAbsolutePath());
 80     }
 81 
 82     private static void zip(ZipOutputStream zos, String file, String pathName) throws IOException {
 83         File file2zip = new File(file);
 84         if (file2zip.isFile()) {
 85             zos.putNextEntry(new ZipEntry(pathName + file2zip.getName()));
 86             IOUtils.copy(new FileInputStream(file2zip.getAbsolutePath()), zos);
 87             zos.flush();
 88             zos.closeEntry();
 89         } else {
 90             File[] files = file2zip.listFiles();
 91             if (ArrayUtils.isNotEmpty(files)) {
 92                 for (File f : files) {
 93                     if (f.isDirectory()) {
 94                         zip(zos, FilenameUtils.normalizeNoEndSeparator(f.getAbsolutePath(), true), 
 95                                 FilenameUtils.normalizeNoEndSeparator(pathName + f.getName(), true) + "/");
 96                     } else {
 97                         zos.putNextEntry(new ZipEntry(pathName + f.getName()));
 98                         IOUtils.copy(new FileInputStream(f.getAbsolutePath()), zos);
 99                         zos.flush();
100                         zos.closeEntry();
101                     }
102                 }
103             }
104         }
105     }
106 
107     /**
108      * 解压
109      *
110      * @param fromZipFile
111      *            zip文件路径
112      * @param unzipPath
113      *            解压路径
114      */
115     @SuppressWarnings("unchecked")
116     public static final void unzip(String fromZipFile, String unzipPath) throws Exception {
117 
118         FileOutputStream fos = null;
119         InputStream is = null;
120         String path1 = StringUtils.EMPTY;
121         String tempPath = StringUtils.EMPTY;
122 
123         if (!new File(unzipPath).exists()) {
124             new File(unzipPath).mkdir();
125         }
126         ZipFile zipFile = null;
127         try {
128             zipFile = new ZipFile(fromZipFile, DEFAULT_CHARSET);
129         } catch (IOException e1) {
130             e1.printStackTrace();
131             throw new Exception(e1);
132         }
133         File temp = new File(unzipPath);
134         String strPath = temp.getAbsolutePath();
135         Enumeration<ZipEntry> enu = zipFile.getEntries();
136         ZipEntry zipEntry = null;
137         while (enu.hasMoreElements()) {
138             zipEntry = (ZipEntry) enu.nextElement();
139             path1 = zipEntry.getName();
140             if (zipEntry.isDirectory()) {
141                 tempPath = FilenameUtils.normalizeNoEndSeparator(strPath + File.separator + path1, true);
142                 File dir = new File(tempPath);
143                 dir.mkdirs();
144                 continue;
145             } else {
146 
147                 BufferedInputStream bis = null;
148                 BufferedOutputStream bos = null;
149                 try {
150                     is = zipFile.getInputStream(zipEntry);
151                     bis = new BufferedInputStream(is);
152                     path1 = zipEntry.getName();
153                     tempPath = FilenameUtils.normalizeNoEndSeparator(strPath + File.separator + path1, true);
154                     FolderUtils.mkdirs(new File(tempPath).getParent());
155                     fos = new FileOutputStream(tempPath);
156                     bos = new BufferedOutputStream(fos);
157 
158                     IOUtils.copy(bis, bos);
159                 } catch (IOException e) {
160                     e.printStackTrace();
161                     throw new Exception(e);
162                 } finally {
163                     IOUtils.closeQuietly(bis);
164                     IOUtils.closeQuietly(bos);
165                     IOUtils.closeQuietly(is);
166                     IOUtils.closeQuietly(fos);
167                 }
168             }
169         }
170     }
171 }

 

转载于:https://www.cnblogs.com/zhoubang521/p/5200623.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
package com.hexiang.utils; import java.io.*; import java.util.*; import java.util.zip.Adler32; import java.util.zip.CheckedInputStream; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import java.util.zip.ZipOutputStream; public class ZipUtils { private static final int BUFFER = 8192; private static void log(String msg){ System.out.println (msg); } private static String getFileName(String filePath){ int index = filePath.indexOf("."); return filePath.substring(0, index); } @SuppressWarnings("unused") private static String getRootPath(String filePath){ int index = filePath.indexOf("."); return filePath.substring(0, index); } public static void zip(String sourceFilePath){ File fileDir = new File(sourceFilePath); if(fileDir.exists()){ log(fileDir.getPath()+" Starting Zip ..."); long startTime = System.currentTimeMillis(); doZip(fileDir); long endTime = System.currentTimeMillis(); long costTime = endTime - startTime; log("Zip Success!"); log("use time -- "+costTime+" millsec!"); }else{ log("can't find the File!"); } } public static void unZip(String zipFilePath){ File fileDir = new File(zipFilePath); if(fileDir.exists()){ log(fileDir.getPath()+" Starting UnZip ..."); long startTime = System.currentTimeMillis(); doUnZip(fileDir); long endTime = System.currentTimeMillis(); long costTime = endTime - startTime; log("UnZip Success!"); log("use time -- "+costTime+" millsec!"); }else{ log("can't find the File!"); } } public static void doZip(File file){ List<File> fileList = new ArrayList<File>(); List<File> allFiles = (ArrayList<File>)searchFiles(file.getPath(), fileList); Object[] fileArray = allFiles.toArray(); BufferedInputStream in = null; FileInputStream fis = null; ZipOutputStream zos = null; FileOutputStream fos = null; try { fos = new FileOutputStream(file.getParent()+File.separator+file.getName()+".zip"); zos = new ZipOutputStream(new BufferedOutputStream(fos, BUFFER)); zos.setLevel(9); byte[] data = new byte [BUFFER]; for (int i = 0; i<fileArray.length; i++){ // 设置压缩文件入口entry,为被读取的文件创建压缩条目 File tempFile = new File(fileArray[i].toString()); String rootStr = file.getPath(); String entryStr = null; // entry以相对路径的形式设置。以文件夹C:\temp例如temp\test.doc或者test.xls 如果设置不当,会出现拒绝访问等错误 // 分别处理单个文件/目录的entry if(rootStr.equals(tempFile.getPath())){ entryStr = tempFile.getName(); }else{ entryStr = tempFile.getPath().substring((rootStr+File.separator).length()); } log(entryStr); ZipEntry entry = new ZipEntry(entryStr); zos.putNextEntry(entry); fis = new FileInputStream(tempFile); in = new BufferedInputStream(fis, BUFFER); int count; while((count = in.read(data, 0, BUFFER)) != -1){ zos.write(data, 0, count); } } } catch (Exception ex) { ex.printStackTrace(); }finally{ try{ if(in != null){ in.close(); } if(zos != null){ zos.close(); } }catch (Exception e) { e.printStackTrace(); } } } public static void doUnZip(File file){ try{ final int BUFFER = 2048; BufferedOutputStream dest = null; FileInputStream fis = new FileInputStream(file); CheckedInputStream checksum = new CheckedInputStream(fis,new Adler32()); ZipInputStream zis = new ZipInputStream(new BufferedInputStream(checksum)); ZipEntry entry; while((entry = zis.getNextEntry()) != null){ log("Extracting: "+entry); int count; byte[] data = new byte[BUFFER]; log("unzip to "+getFileName(file.getPath())); FileOutputStream fos = new FileOutputStream(getFileName(file.getPath())+File.separator+newDir(file, entry.getName())); dest = new BufferedOutputStream(fos, BUFFER); while((count = zis.read(data, 0, BUFFER)) != -1){ dest.write(data, 0, count); } dest.flush(); dest.close(); } zis.close(); System.out.println("Checksum: "+checksum.getChecksum().getValue()); }catch(Exception e){ e.printStackTrace(); } } public static List<File> searchFiles(String sourceFilePath, List<File> fileList){ File fileDir = new File(sourceFilePath); if(fileDir.isDirectory()){ File[] subfiles = fileDir.listFiles(); for(int i = 0; i<subfiles.length; i++){ searchFiles(subfiles[i].getPath(),fileList); } }else{ fileList.add(fileDir); } return fileList; } @SuppressWarnings("static-access") private static String newDir(File file,String entryName) { String rootDir=getFileName(file.getPath()); log("root:"+rootDir); int index = entryName.lastIndexOf("\\"); String dirStr=new File(rootDir).getParent(); log(dirStr); if (index != -1) { String path=entryName.substring(0, index); log("new Dir:"+rootDir+file.separator+path); new File(rootDir+file.separator+path).mkdirs(); log("entry:"+entryName.substring(0, index)); } else{ new File(rootDir).mkdirs(); log("entry:"+entryName); } return entryName; } }

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值