压缩和解压文件的工具类(ant-1.8.4.jar)

来源:互联网 发布:科比0506赛季得分数据 编辑:程序博客网 时间:2024/05/22 03:43

使用ant-1.8.4.jar中的org.apache.tools.zip包进行文件的文件压缩和解压,主要使用该jar包中的以下类:

org.apache.tools.zip.ZipEntry;
org.apache.tools.zip.ZipFile;
org.apache.tools.zip.ZipOutputStream;

下载地址为:

http://ant.apache.org/

下面是我写的压缩和解压文件的工具类,并附测试,请大家为我debug:

[java] view plaincopy
  1. import java.io.BufferedInputStream;  
  2. import java.io.BufferedOutputStream;  
  3. import java.io.File;  
  4. import java.io.FileInputStream;  
  5. import java.io.FileNotFoundException;  
  6. import java.io.FileOutputStream;  
  7. import java.io.IOException;  
  8. import java.util.ArrayList;  
  9. import java.util.Enumeration;  
  10. import java.util.List;  
  11. import java.util.zip.CRC32;  
  12. import java.util.zip.CheckedOutputStream;  
  13. import java.util.zip.Deflater;  
  14. import java.util.zip.ZipException;  
  15.   
  16. import org.apache.tools.zip.ZipEntry;  
  17. import org.apache.tools.zip.ZipFile;  
  18. import org.apache.tools.zip.ZipOutputStream;  
  19.   
  20. /** 
  21.   * @Description:  
  22.   *     压缩和解压工具 
  23.  */  
  24. public class ZipUtil {  
  25.   
  26.     /** 
  27.       * @Description:  
  28.       *     压缩文件 
  29.       * @param sourcePath 将要压缩的文件或目录的路径,请使用绝对路径 
  30.       * @param zipPath 生成压缩文件的路径,请使用绝对路径。如果该路径以“.zip”为结尾, 
  31.       *         则压缩文件的名称为此路径;如果该路径不以“.zip”为结尾,则压缩文件的名称 
  32.       *         为该路径加上将要压缩的文件或目录的名称,再加上以“.zip”结尾 
  33.       * @param encoding 压缩编码 
  34.       * @param comment 压缩注释 
  35.      */  
  36.     public static void compress(String sourcePath, String zipPath, String encoding, String comment)  
  37.             throws FileNotFoundException, IOException {  
  38.         // 判断要压缩的文件是否存在  
  39.         File sourceFile = new File(sourcePath);  
  40.         if (!sourceFile.exists() || (sourceFile.isDirectory() && sourceFile.list().length == 0)) {  
  41.             throw new FileNotFoundException("要压缩的文件或目录不存在,或者要压缩的目录为空");  
  42.         }  
  43.         // 设置压缩文件路径,默认为将要压缩的路径的父目录为压缩文件的父目录  
  44.         if (zipPath == null || "".equals(zipPath)) {  
  45.             String sourcePathName = sourceFile.getAbsolutePath();  
  46.             int index = sourcePathName.lastIndexOf(".");  
  47.             zipPath = (index > -1 ? sourcePathName.substring(0, index) : sourcePathName) + ".zip";  
  48.         } else {  
  49.             // 如果压缩路径为目录,则将要压缩的文件或目录名做为压缩文件的名字,这里压缩路径不以“.zip”为结尾则认为压缩路径为目录  
  50.             if(!zipPath.endsWith(".zip")){  
  51.                 // 如果将要压缩的路径为目录,则以此目录名为压缩文件名;如果将要压缩的路径为文件,则以此文件名(去除扩展名)为压缩文件名  
  52.                 String fileName = sourceFile.getName();  
  53.                 int index = fileName.lastIndexOf(".");  
  54.                 zipPath = zipPath + File.separator + (index > -1 ? fileName.substring(0, index) : fileName) + ".zip";  
  55.             }  
  56.         }  
  57.         // 设置解压编码  
  58.         if (encoding == null || "".equals(encoding)) {  
  59.             encoding = "GBK";  
  60.         }  
  61.         // 要创建的压缩文件的父目录不存在,则创建  
  62.         File zipFile = new File(zipPath);  
  63.         if (!zipFile.getParentFile().exists()) {  
  64.             zipFile.getParentFile().mkdirs();  
  65.         }  
  66.         // 创建压缩文件输出流  
  67.         FileOutputStream fos = null;  
  68.         try {  
  69.             fos = new FileOutputStream(zipPath);  
  70.         } catch (FileNotFoundException e) {  
  71.             if (fos != null) {  
  72.                 try{ fos.close(); } catch (Exception e1) {}  
  73.             }  
  74.         }  
  75.         // 使用指定校验和创建输出流  
  76.         CheckedOutputStream csum = new CheckedOutputStream(fos, new CRC32());  
  77.         // 创建压缩流  
  78.         ZipOutputStream zos = new ZipOutputStream(csum);  
  79.         // 设置编码,支持中文  
  80.         zos.setEncoding(encoding);  
  81.         // 设置压缩包注释  
  82.         zos.setComment(comment);  
  83.         // 启用压缩  
  84.         zos.setMethod(ZipOutputStream.DEFLATED);  
  85.         // 设置压缩级别为最强压缩  
  86.         zos.setLevel(Deflater.BEST_COMPRESSION);  
  87.         // 压缩文件缓冲流  
  88.         BufferedOutputStream bout = null;  
  89.         try {  
  90.             // 封装压缩流为缓冲流  
  91.             bout = new BufferedOutputStream(zos);  
  92.             // 对数据源进行压缩  
  93.             compressRecursive(zos, bout, sourceFile, sourceFile.getParent());  
  94.         } finally {  
  95.             if (bout != null) {  
  96.                 try{ bout.close(); } catch (Exception e) {}  
  97.             }  
  98.         }  
  99.     }  
  100.   
  101.     /** 
  102.       * @Description:  
  103.       *     压缩文件,支持将多个文件或目录压缩到同一个压缩文件中 
  104.       * @param sourcePath 将要压缩的文件或目录的路径的集合,请使用绝对路径 
  105.       * @param zipPath 生成压缩文件的路径,请使用绝对路径。该路不能为空,并且必须以“.zip”为结尾 
  106.       * @param encoding 压缩编码 
  107.       * @param comment 压缩注释 
  108.      */  
  109.     public static void compress(List<String> sourcePaths, String zipPath, String encoding, String comment)  
  110.             throws FileNotFoundException, IOException {  
  111.         // 设置压缩文件路径,默认为将要压缩的路径的父目录为压缩文件的父目录  
  112.         if (zipPath == null || "".equals(zipPath) || !zipPath.endsWith(".zip")) {  
  113.             throw new FileNotFoundException("必须指定一个压缩路径,而且该路径必须以'.zip'为结尾");  
  114.         }  
  115.         // 设置解压编码  
  116.         if (encoding == null || "".equals(encoding)) {  
  117.             encoding = "GBK";  
  118.         }  
  119.         // 要创建的压缩文件的父目录不存在,则创建  
  120.         File zipFile = new File(zipPath);  
  121.         if (!zipFile.getParentFile().exists()) {  
  122.             zipFile.getParentFile().mkdirs();  
  123.         }  
  124.         // 创建压缩文件输出流  
  125.         FileOutputStream fos = null;  
  126.         try {  
  127.             fos = new FileOutputStream(zipPath);  
  128.         } catch (FileNotFoundException e) {  
  129.             if (fos != null) {  
  130.                 try{ fos.close(); } catch (Exception e1) {}  
  131.             }  
  132.         }  
  133.         // 使用指定校验和创建输出流  
  134.         CheckedOutputStream csum = new CheckedOutputStream(fos, new CRC32());  
  135.         // 创建压缩流  
  136.         ZipOutputStream zos = new ZipOutputStream(csum);  
  137.         // 设置编码,支持中文  
  138.         zos.setEncoding(encoding);  
  139.         // 设置压缩包注释  
  140.         zos.setComment(comment);  
  141.         // 启用压缩  
  142.         zos.setMethod(ZipOutputStream.DEFLATED);  
  143.         // 设置压缩级别为最强压缩  
  144.         zos.setLevel(Deflater.BEST_COMPRESSION);  
  145.         // 压缩文件缓冲流  
  146.         BufferedOutputStream bout = null;  
  147.         try {  
  148.             // 封装压缩流为缓冲流  
  149.             bout = new BufferedOutputStream(zos);  
  150.             // 迭代压缩每一个路径  
  151.             for (int i=0,len=sourcePaths.size(); i<len; i++) {  
  152.                 // 获取每一个压缩路径  
  153.                 File sourceFile = new File(sourcePaths.get(i));  
  154.                 // 对数据源进行压缩  
  155.                 compressRecursive(zos, bout, sourceFile, sourceFile.getParent());  
  156.             }  
  157.         } finally {  
  158.             if (bout != null) {  
  159.                 try{ bout.close(); } catch (Exception e) {}  
  160.             }  
  161.         }  
  162.     }  
  163.       
  164.     /** 
  165.       * @Description:  
  166.       *     压缩文件时,所使用的迭代方法 
  167.       * @param zos 压缩输出流 
  168.       * @param bout 封装压缩输出流的缓冲流 
  169.       * @param sourceFile 将要压缩的文件或目录的路径 
  170.       * @param prefixDir 整个将要压缩的文件或目录的父目录,传入此值为了获取压缩条目的名称 
  171.      */  
  172.     private static void compressRecursive(ZipOutputStream zos, BufferedOutputStream bout,  
  173.             File sourceFile, String prefixDir) throws IOException, FileNotFoundException {  
  174.         // 获取压缩条目名,初始时将要压缩的文件或目录的相对路径  
  175.         String entryName = sourceFile.getAbsolutePath().substring(prefixDir.length() + File.separator.length());  
  176.         // 判断是文件还是目录,如果是目录,则继续迭代压缩  
  177.         if (sourceFile.isDirectory()) {  
  178.             // 如果是目录,则需要在目录后面加上分隔符('/')  
  179.             //ZipEntry zipEntry = new ZipEntry(entryName + File.separator);  
  180.             //zos.putNextEntry(zipEntry);  
  181.             // 获取目录中的文件,然后迭代压缩  
  182.             File[] srcFiles = sourceFile.listFiles();  
  183.             for (int i = 0; i < srcFiles.length; i++) {  
  184.                 // 压缩  
  185.                 compressRecursive(zos, bout, srcFiles[i], prefixDir);  
  186.             }  
  187.         } else {  
  188.             // 开始写入新的ZIP文件条目并将流定位到条目数据的开始处  
  189.             ZipEntry zipEntry = new ZipEntry(entryName);  
  190.             // 向压缩流中写入一个新的条目  
  191.             zos.putNextEntry(zipEntry);  
  192.             // 读取将要压缩的文件的输入流  
  193.             BufferedInputStream bin = null;  
  194.             try{  
  195.                 // 获取输入流读取文件  
  196.                 bin = new BufferedInputStream(new FileInputStream(sourceFile));  
  197.                 // 读取文件,并写入压缩流  
  198.                 byte[] buffer = new byte[1024];  
  199.                 int readCount = -1;  
  200.                 while ((readCount = bin.read(buffer)) != -1) {  
  201.                     bout.write(buffer, 0, readCount);  
  202.                 }  
  203.                 // 注,在使用缓冲流写压缩文件时,一个条件完后一定要刷新,不然可能有的内容就会存入到后面条目中去了  
  204.                 bout.flush();  
  205.                 // 关闭当前ZIP条目并定位流以写入下一个条目  
  206.                 zos.closeEntry();  
  207.             } finally {  
  208.                 if (bin != null) {  
  209.                     try { bin.close(); } catch (IOException e) {}  
  210.                 }  
  211.             }  
  212.         }  
  213.     }  
  214.       
  215.     /** 
  216.       * @Description:  
  217.       *     解压文件 
  218.       * @param zipPath 被压缩文件,请使用绝对路径 
  219.       * @param targetPath 解压路径,解压后的文件将会放入此目录中,请使用绝对路径 
  220.       *         默认为压缩文件的路径的父目录为解压路径 
  221.       * @param encoding 解压编码 
  222.      */  
  223.     public static void decompress(String zipPath, String targetPath, String encoding)  
  224.             throws FileNotFoundException, ZipException, IOException {  
  225.         // 获取解缩文件  
  226.         File file = new File(zipPath);  
  227.         if (!file.isFile()) {  
  228.             throw new FileNotFoundException("要解压的文件不存在");  
  229.         }  
  230.         // 设置解压路径  
  231.         if (targetPath == null || "".equals(targetPath)) {  
  232.             targetPath = file.getParent();  
  233.         }  
  234.         // 设置解压编码  
  235.         if (encoding == null || "".equals(encoding)) {  
  236.             encoding = "GBK";  
  237.         }  
  238.         // 实例化ZipFile对象  
  239.         ZipFile zipFile = new ZipFile(file, encoding);  
  240.         // 获取ZipFile中的条目  
  241.         Enumeration<ZipEntry> files = zipFile.getEntries();  
  242.         // 迭代中的每一个条目  
  243.         ZipEntry entry = null;  
  244.         // 解压后的文件  
  245.         File outFile = null;  
  246.         // 读取压缩文件的输入流  
  247.         BufferedInputStream bin = null;  
  248.         // 写入解压后文件的输出流  
  249.         BufferedOutputStream bout = null;  
  250.         while (files.hasMoreElements()) {  
  251.             // 获取解压条目  
  252.             entry = files.nextElement();  
  253.             // 实例化解压后文件对象  
  254.             outFile = new File(targetPath + File.separator + entry.getName());  
  255.             // 如果条目为目录,则跳向下一个  
  256.             if (entry.getName().endsWith(File.separator)) {  
  257.                 outFile.mkdirs();  
  258.                 continue;  
  259.             }  
  260.             // 创建目录  
  261.             if (!outFile.getParentFile().exists()) {  
  262.                 outFile.getParentFile().mkdirs();  
  263.             }  
  264.             // 创建新文件  
  265.             outFile.createNewFile();  
  266.             // 如果不可写,则跳向下一个条目  
  267.             if (!outFile.canWrite()) {  
  268.                 continue;  
  269.             }  
  270.             try {  
  271.                 // 获取读取条目的输入流  
  272.                 bin = new BufferedInputStream(zipFile.getInputStream(entry));  
  273.                 // 获取解压后文件的输出流  
  274.                 bout = new BufferedOutputStream(new FileOutputStream(outFile));  
  275.                 // 读取条目,并写入解压后文件  
  276.                 byte[] buffer = new byte[1024];  
  277.                 int readCount = -1;  
  278.                 while ((readCount = bin.read(buffer)) != -1) {  
  279.                     bout.write(buffer, 0, readCount);  
  280.                 }  
  281.             } finally {  
  282.                 try {  
  283.                     bin.close();  
  284.                     bout.flush();  
  285.                     bout.close();  
  286.                 } catch (Exception e) {}  
  287.             }  
  288.         }  
  289.     }  
  290.       
  291.     public static void main(String[] args) throws Exception{  
  292.         //compressTest();  
  293.         //compressTest2();  
  294.         //decompressTest();  
  295.     }  
  296.       
  297.     public static void compressTest() throws Exception {  
  298.         String sourcePath = "E:" + File.separator + "文档" + File.separator + "音乐";  
  299.         String zipPath = "E:" + File.separator + "我的音乐.zip";  
  300.         String comment = "音乐压缩文件";  
  301.         compress(sourcePath, zipPath, "GBK", comment);  
  302.     }  
  303.       
  304.     public static void decompressTest() throws Exception {  
  305.         String zipPath = "E:" + File.separator + "我的音乐.zip";  
  306.         String targetPath = "E:" + File.separator + "temp";  
  307.         decompress(zipPath, targetPath, "GBK");  
  308.     }  
  309.       
  310.     public static void compressTest2() throws Exception {  
  311.         List<String> list = new ArrayList<String>();  
  312.         list.add("E:" + File.separator + "文档" + File.separator + "音乐");  
  313.         list.add("E:" + File.separator + "文档" + File.separator + "视频");  
  314.         list.add("E:" + File.separator + "文档" + File.separator + "资料");  
  315.         list.add("E:" + File.separator + "文档" + File.separator + "书籍");  
  316.         String zipPath = "E:" + File.separator + "我的文档压缩文件.zip";  
  317.         String comment = "我的文档压缩文件";  
  318.         compress(list, zipPath, "GBK", comment);  
  319.     }  
  320.       
  321. }  
0 0
原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 宝宝不会喝奶粉怎么办 两个月宝宝不长肉怎么办 打疫苗后发烧怎么办 孕期不爱吃水果怎么办 孕期很少吃水果怎么办 三个月小孩不吃奶粉怎么办 三个月宝宝偏瘦怎么办 破壁机打果汁有沫怎么办 宝宝7个月坐不稳怎么办 婴儿头睡偏了怎么办天 宝宝不爱趴着怎么办 宝宝喜欢竖着抱怎么办 婴儿抱习惯了怎么办 新生儿总让抱着放下就哭可怎么办 三个月宝宝认人怎么办 三个月的宝宝认生怎么办 一岁半宝宝尿黄怎么办 一岁多宝宝尿少怎么办 1岁宝宝一晚没尿怎么办 抗利尿激素少怎么办 小孩夜里尿多怎么办 一岁宝宝认生怎么办 婴儿一个月认生怎么办 婴儿大便带血丝怎么办 两个月宝宝认生怎么办 晚上宝宝认人怎么办 小孩长白头发怎么办 三个月婴儿脚力不足怎么办 未满月宝宝便秘怎么办 婴儿5天没拉大便怎么办 儿童三天没大便怎么办 婴儿4天没拉大便了怎么办 孩子不天天排便怎么办 宝宝便秘5天怎么办 小孩子3天便秘怎么办 宝宝4天没拉大便怎么办 儿童不拉大便怎么办 吃母乳没有大便怎么办 婴儿老是抓头皮怎么办 婴儿两天不大便怎么办 不排便怎么办小窍门