java对文件压缩与解压缩操作

1. 文件的压缩
[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. /** 
  2.      * 压缩文件,支持文件和目录 
  3.      * @param srcFile 待压缩的文件 
  4.      * @param desPathName 压缩后的文件名(带路径) 
  5.      */  
  6.     public static void zip(File srcFile, String desPathName) {  
  7.         if (!srcFile.exists()) {  
  8.             log.error("文件{}不存在:", srcFile.getAbsolutePath());  
  9.             return;  
  10.         }  
  11.         try {  
  12.             FileOutputStream fileOutputStream = new FileOutputStream(desPathName);  
  13.             CheckedOutputStream cos = new CheckedOutputStream(fileOutputStream, new CRC32());  
  14.             ZipOutputStream out = new ZipOutputStream(cos);  
  15.             zipByType(srcFile, out, "");  
  16.             out.close();  
  17.         } catch (Exception e) {  
  18.             log.error("压缩文件异常:", e);  
  19.             return;  
  20.         }  
  21.     }  
  22.     /** 
  23.      * 判断是目录还是文件,根据类型(文件/文件夹)执行不同的压缩方法 
  24.      * @param file 待压缩的文件 
  25.      * @param out 文件压缩流 
  26.      * @param basedir 压缩文件里面的相对路径 
  27.      */  
  28.     private static void zipByType(File file, ZipOutputStream out, String basedir) {  
  29.         /* 判断是目录还是文件 */  
  30.         if (file.isDirectory()) {  
  31.             zipDirectory(file, out, basedir);  
  32.         } else {  
  33.             zipFile(file, out, basedir);  
  34.         }  
  35.     }  
  36.     /** 
  37.      * 压缩一个目录 
  38.      * @param dir 待压缩的目录 
  39.      * @param out 文件压缩流 
  40.      * @param basedir 压缩文件里面的相对路径 
  41.      */  
  42.     private static void zipDirectory(File dir, ZipOutputStream out, String basedir) {  
  43.         if (!dir.exists()) {  
  44.             log.error("文件{}不存在:", dir.getAbsolutePath());  
  45.             return;  
  46.         }  
  47.         File[] files = dir.listFiles();  
  48.         for (int i = 0; i < files.length; i++) {  
  49.             /* 递归 */  
  50.             zipByType(files[i], out, basedir + dir.getName() + "/");  
  51.         }  
  52.     }  
  53.     /** 
  54.      * 压缩一个文件 
  55.      * @param file 待压缩的文件 
  56.      * @param out 压缩流 
  57.      * @param basedir 压缩文件里面的相对路径 
  58.      */  
  59.     private static void zipFile(File file, ZipOutputStream out, String basedir) {  
  60.         if (!file.exists()) {  
  61.             log.error("文件{}不存在", file.getAbsolutePath());  
  62.             return;  
  63.         }  
  64.         try {  
  65.             BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));  
  66.             ZipEntry entry = new ZipEntry(basedir + file.getName());  
  67.             out.putNextEntry(entry);  
  68.             int count;  
  69.             byte data[] = new byte[8192];  
  70.             while ((count = bis.read(data, 0, data.length)) != -1) {  
  71.                 out.write(data, 0, count);  
  72.             }  
  73.             bis.close();  
  74.         } catch (Exception e) {  
  75.             log.error("压缩文件异常:", e);  
  76.             return;  
  77.         }  
  78.     }  
2. 文件的解压缩
[html]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. /**  
  2.      * 解压缩文件操作  
  3.      *   
  4.      * @param srcPathName  
  5.      *            被解压的压缩文件名(带路径)  
  6.      * @param desPathName  
  7.      *            解压后的目录  
  8.      */  
  9.     public static void unzip(String zipFileName, String desPathName) {  
  10.         File zipFile = new File(zipFileName);  
  11.         unzip(zipFile, desPathName);  
  12.     }  
  13.     /**  
  14.      * 解压缩文件操作  
  15.      *   
  16.      * @param zipFile  
  17.      *            被解压的压缩文件  
  18.      * @param targetPath  
  19.      *            解压后的目录  
  20.      */  
  21.     public static void unzip(File zipFile, String targetPath) {  
  22.         if (!zipFile.exists()) {  
  23.             log.error("文件{}不存在", zipFile.getAbsolutePath());  
  24.         }  
  25.         try {  
  26.             File pathFile = new File(targetPath);  
  27.             if (!pathFile.exists()) {  
  28.                 pathFile.mkdirs();  
  29.             }  
  30.             ZipFile zip = new ZipFile(zipFile);  
  31.             for (Enumeration<? extends ZipEntry> entries = zip.entries(); entries.hasMoreElements();) {  
  32.                 ZipEntry entry = (ZipEntry) entries.nextElement();  
  33.                   
  34.                 String zipEntryName = entry.getName();  
  35.                 InputStream in = zip.getInputStream(entry);  
  36.                 String outPath = (targetPath + zipEntryName).replaceAll("\\*", "/");  
  37.                 // 判断路径是否存在,不存在则创建文件路径  
  38.                 if (outPath.indexOf('/') > 0) {  
  39.                     File file = new File(outPath.substring(0, outPath.lastIndexOf('/')));  
  40.                     if (!file.exists()) {  
  41.                         file.mkdirs();  
  42.                     }  
  43.                 }  
  44.                 // 判断文件全路径是否为文件夹,如果是上面已经创建,不需要解压  
  45.                 if (new File(outPath).isDirectory()) {  
  46.                     continue;  
  47.                 }  
  48.                 OutputStream out = new FileOutputStream(outPath);  
  49.                 byte[] buf1 = new byte[1024];  
  50.                 int len;  
  51.                 while ((len = in.read(buf1)) > 0) {  
  52.                     out.write(buf1, 0, len);  
  53.                 }  
  54.                 in.close();  
  55.                 out.close();  
  56.             }  
  57.             zip.close();  
  58.         } catch (IOException e) {  
  59.             log.error("解压缩文件异常:", e);  
  60.             return;  
  61.         }  
  62.     }  
3. 附工具类ZipUtil.java
[html]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. package com.morris.util.file;  
  2. import java.io.BufferedInputStream;  
  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.io.OutputStream;  
  9. import java.util.Enumeration;  
  10. import java.util.zip.CRC32;  
  11. import java.util.zip.CheckedOutputStream;  
  12. import java.util.zip.ZipEntry;  
  13. import java.util.zip.ZipFile;  
  14. import java.util.zip.ZipOutputStream;  
  15. import org.slf4j.Logger;  
  16. import org.slf4j.LoggerFactory;  
  17. /**  
  18.  * 文件的压缩与解压  
  19.  * @author Morris  
  20.  *  
  21.  */  
  22. public class ZipUtil {  
  23.       
  24.     private static final transient Logger log = LoggerFactory.getLogger(ZipUtil.class);  
  25.     // ------------------------------压缩文件begin----------------------------------------  
  26.     /**  
  27.      * 压缩文件,支持文件和目录  
  28.      * @param srcPathName 被压缩的文件名(带路径),压缩到当前目录下  
  29.      */  
  30.     public static void zip(String srcPathName) {  
  31.         zip(new File(srcPathName));  
  32.     }  
  33.     /**  
  34.      * 执行压缩文件操作,支持文件和文件夹  
  35.      *   
  36.      * @param srcFile 被压缩的文件,压缩到当前目录下  
  37.      */  
  38.     public static void zip(File srcFile) {  
  39.         if (!srcFile.exists()) {  
  40.             log.info("文件{}不存在!", srcFile.getAbsolutePath());              
  41.         }  
  42.         String desFileName = srcFile.getName();  
  43.         if (!srcFile.isDirectory()) {  
  44.             desFileName = desFileName.substring(0, desFileName.lastIndexOf("."));  
  45.         }  
  46.         desFileName += ".zip";  
  47.         String desFile = srcFile.getParent() + "/" + desFileName;  
  48.         zip(srcFile, desFile);  
  49.     }  
  50.     /**  
  51.      * 执行压缩文件操作,支持文件和文件夹  
  52.      *   
  53.      * @param srcPathName  
  54.      *            被压缩的文件名(带路径)  
  55.      * @param desPathName  
  56.      *            压缩后的文件名(带路径)  
  57.      */  
  58.     public static void zip(String srcPathName, String desPathName) {  
  59.         File srcFile = new File(srcPathName);  
  60.         zip(srcFile, desPathName);  
  61.     }  
  62.     /**  
  63.      * 压缩文件,支持文件和目录  
  64.      * @param srcFile 待压缩的文件  
  65.      * @param desPathName 压缩后的文件名(带路径)  
  66.      */  
  67.     public static void zip(File srcFile, String desPathName) {  
  68.         if (!srcFile.exists()) {  
  69.             log.error("文件{}不存在:", srcFile.getAbsolutePath());  
  70.             return;  
  71.         }  
  72.         try {  
  73.             FileOutputStream fileOutputStream = new FileOutputStream(desPathName);  
  74.             CheckedOutputStream cos = new CheckedOutputStream(fileOutputStream, new CRC32());  
  75.             ZipOutputStream out = new ZipOutputStream(cos);  
  76.             zipByType(srcFile, out, "");  
  77.             out.close();  
  78.         } catch (Exception e) {  
  79.             log.error("压缩文件异常:", e);  
  80.             return;  
  81.         }  
  82.     }  
  83.     /**  
  84.      * 判断是目录还是文件,根据类型(文件/文件夹)执行不同的压缩方法  
  85.      * @param file 待压缩的文件  
  86.      * @param out 文件压缩流  
  87.      * @param basedir 压缩文件里面的相对路径  
  88.      */  
  89.     private static void zipByType(File file, ZipOutputStream out, String basedir) {  
  90.         /* 判断是目录还是文件 */  
  91.         if (file.isDirectory()) {  
  92.             zipDirectory(file, out, basedir);  
  93.         } else {  
  94.             zipFile(file, out, basedir);  
  95.         }  
  96.     }  
  97.     /**  
  98.      * 压缩一个目录  
  99.      * @param dir 待压缩的目录  
  100.      * @param out 文件压缩流  
  101.      * @param basedir 压缩文件里面的相对路径  
  102.      */  
  103.     private static void zipDirectory(File dir, ZipOutputStream out, String basedir) {  
  104.         if (!dir.exists()) {  
  105.             log.error("文件{}不存在:", dir.getAbsolutePath());  
  106.             return;  
  107.         }  
  108.         File[] files = dir.listFiles();  
  109.         for (int i = 0; i < files.length; i++) {  
  110.             /* 递归 */  
  111.             zipByType(files[i], out, basedir + dir.getName() + "/");  
  112.         }  
  113.     }  
  114.     /**  
  115.      * 压缩一个文件  
  116.      * @param file 待压缩的文件  
  117.      * @param out 压缩流  
  118.      * @param basedir 压缩文件里面的相对路径  
  119.      */  
  120.     private static void zipFile(File file, ZipOutputStream out, String basedir) {  
  121.         if (!file.exists()) {  
  122.             log.error("文件{}不存在", file.getAbsolutePath());  
  123.             return;  
  124.         }  
  125.         try {  
  126.             BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));  
  127.             ZipEntry entry = new ZipEntry(basedir + file.getName());  
  128.             out.putNextEntry(entry);  
  129.             int count;  
  130.             byte data[] = new byte[8192];  
  131.             while ((count = bis.read(data, 0, data.length)) != -1) {  
  132.                 out.write(data, 0, count);  
  133.             }  
  134.             bis.close();  
  135.         } catch (Exception e) {  
  136.             log.error("压缩文件异常:", e);  
  137.             return;  
  138.         }  
  139.     }  
  140.     // ------------------------------压缩文件end------------------------------------------  
  141.     // ------------------------------解压缩文件begin--------------------------------------  
  142.     /**  
  143.      * 解压缩文件操作,解压到到当前目录下  
  144.      *   
  145.      * @param zipFile  
  146.      *            被解压的压缩文件名(带路径)  
  147.      */  
  148.     public static void unzip(String zipFileName) {  
  149.         File zipFile = new File(zipFileName);  
  150.         unzip(zipFile);  
  151.     }  
  152.     /**  
  153.      * 解压缩文件操作,解压到到当前目录下  
  154.      *   
  155.      * @param zipFile  
  156.      *            被解压的压缩文件  
  157.      */  
  158.     public static void unzip(File zipFile) {  
  159.         if (!zipFile.exists()) {  
  160.             log.error("文件{}不存在", zipFile.getAbsolutePath());  
  161.         }  
  162.         String targetPath = zipFile.getParent() + "/";  
  163.         unzip(zipFile, targetPath);  
  164.     }  
  165.     /**  
  166.      * 解压缩文件操作  
  167.      *   
  168.      * @param srcPathName  
  169.      *            被解压的压缩文件名(带路径)  
  170.      * @param desPathName  
  171.      *            解压后的目录  
  172.      */  
  173.     public static void unzip(String zipFileName, String desPathName) {  
  174.         File zipFile = new File(zipFileName);  
  175.         unzip(zipFile, desPathName);  
  176.     }  
  177.     /**  
  178.      * 解压缩文件操作  
  179.      *   
  180.      * @param zipFile  
  181.      *            被解压的压缩文件  
  182.      * @param targetPath  
  183.      *            解压后的目录  
  184.      */  
  185.     public static void unzip(File zipFile, String targetPath) {  
  186.         if (!zipFile.exists()) {  
  187.             log.error("文件{}不存在", zipFile.getAbsolutePath());  
  188.         }  
  189.         try {  
  190.             File pathFile = new File(targetPath);  
  191.             if (!pathFile.exists()) {  
  192.                 pathFile.mkdirs();  
  193.             }  
  194.             ZipFile zip = new ZipFile(zipFile);  
  195.             for (Enumeration<? extends ZipEntry> entries = zip.entries(); entries.hasMoreElements();) {  
  196.                 ZipEntry entry = (ZipEntry) entries.nextElement();  
  197.                   
  198.                 String zipEntryName = entry.getName();  
  199.                 InputStream in = zip.getInputStream(entry);  
  200.                 String outPath = (targetPath + zipEntryName).replaceAll("\\*", "/");  
  201.                 // 判断路径是否存在,不存在则创建文件路径  
  202.                 if (outPath.indexOf('/') > 0) {  
  203.                     File file = new File(outPath.substring(0, outPath.lastIndexOf('/')));  
  204.                     if (!file.exists()) {  
  205.                         file.mkdirs();  
  206.                     }  
  207.                 }  
  208.                 // 判断文件全路径是否为文件夹,如果是上面已经创建,不需要解压  
  209.                 if (new File(outPath).isDirectory()) {  
  210.                     continue;  
  211.                 }  
  212.                 OutputStream out = new FileOutputStream(outPath);  
  213.                 byte[] buf1 = new byte[1024];  
  214.                 int len;  
  215.                 while ((len = in.read(buf1)) > 0) {  
  216.                     out.write(buf1, 0, len);  
  217.                 }  
  218.                 in.close();  
  219.                 out.close();  
  220.             }  
  221.             zip.close();  
  222.         } catch (IOException e) {  
  223.             log.error("解压缩文件异常:", e);  
  224.             return;  
  225.         }  
  226.     }  
  227.     // ------------------------------解压缩文件end----------------------------------------  
  228. }  
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值