Android实现文件压缩与解压缩

来源:互联网 发布:英语分级阅读 知乎 编辑:程序博客网 时间:2024/06/05 22:49

转自:http://zhourrr1234-126-com.iteye.com/blog/2217935

此篇博客主要是记录如何对文件夹进行压缩以及解压缩操作,结合网上多位大侠的文章,针对自己的情况改动了下,废话不多说

直接上代码:(压缩与解压缩有两种不同的实现方法,选其一即可)

首先是压缩操作:

Java代码  收藏代码
  1. /** 
  2.      * [对指定路径下文件的压缩处理] 
  3.      * [功能详细描述] 
  4.      * @param src 径地址 
  5.      * @param archive 指定到压缩文件夹的路径 
  6.      * @param comment 描述 
  7.      * @throws FileNotFoundException 文件没有找到异常 
  8.      * @throws IOException  IO输入异常 
  9.      */  
  10.     public void writeByApacheZipOutputStream(String[] src, String archive,  
  11.             String comment) throws FileNotFoundException, IOException {  
  12.         Log.e(TAG, "writeByApacheZipOutputStream");  
  13.         // ----压缩文件:  
  14.         FileOutputStream f = new FileOutputStream(archive);  
  15.         // 使用指定校验和创建输出流  
  16.         CheckedOutputStream csum = new CheckedOutputStream(f, new CRC32());  
  17.         ZipOutputStream zos = new ZipOutputStream(csum);  
  18.         // 支持中文  
  19.         zos.setEncoding("GBK");  
  20.         BufferedOutputStream out = new BufferedOutputStream(zos);  
  21.         // 设置压缩包注释  
  22.         zos.setComment(comment);  
  23.         // 启用压缩  
  24.         zos.setMethod(ZipOutputStream.DEFLATED);  
  25.         // 压缩级别为最强压缩,但时间要花得多一点  
  26.         zos.setLevel(Deflater.BEST_COMPRESSION);  
  27.         // 如果为单个文件的压缩在这里修改  
  28.         for (int i = 0; i < src.length; i++) {  
  29.             File srcFile = new File(src[i]);  
  30.             if (!srcFile.exists()  
  31.                     || (srcFile.isDirectory() && srcFile.list().length == 0)) {  
  32.                 Log.e(TAG, "!srcFile.exists()");  
  33.                 throw new FileNotFoundException(  
  34.                         "File must exist and ZIP file must have at least one entry.");  
  35.             }  
  36.             String strSrcString = src[i];  
  37.             // 获取压缩源所在父目录  
  38.             strSrcString = strSrcString.replaceAll("////""/");  
  39.             String prefixDir = null;  
  40.             if (srcFile.isFile()) {  
  41.                 prefixDir = strSrcString.substring(0,  
  42.                         strSrcString.lastIndexOf("/") + 1);  
  43.             } else {  
  44.                 prefixDir = (strSrcString.replaceAll("/$""") + "/");  
  45.             }  
  46.             // 如果不是根目录  
  47.             if (prefixDir.indexOf("/") != (prefixDir.length() - 1)  
  48.                     && isCreateSrcDir) {  
  49.                 prefixDir = prefixDir.replaceAll("[^/]+/$""");  
  50.             }  
  51.             // 开始压缩  
  52.             writeRecursive(zos, out, srcFile, prefixDir);  
  53.         }  
  54.         out.close();  
  55.         // 注:校验和要在流关闭后才准备,一定要放在流被关闭后使用  
  56.         Log.e(TAG, "Checksum: " + csum.getChecksum().getValue());  
  57.         @SuppressWarnings("unused")  
  58.         BufferedInputStream bi;  
  59.     }  
  60.   
  61.      /** 
  62.      * [递归压缩 使用 org.apache.tools.zip.ZipOutputStream 类进行压缩,它的好处就是支持中文路径, 
  63.      * 而Java类库中的 java.util.zip.ZipOutputStream 压缩中文文件名时压缩包会出现乱码。 使用 apache 
  64.      * 中的这个类与 java 类库中的用法是一新的,只是能设置编码方式了。]<BR> 
  65.      * [功能详细描述] 
  66.      * @param zos 
  67.      * @param bo 
  68.      * @param srcFile 
  69.      * @param prefixDir 
  70.      * @throws IOException 
  71.      * @throws FileNotFoundException 
  72.      */  
  73.     private static void writeRecursive(ZipOutputStream zos,  
  74.             BufferedOutputStream bo, File srcFile, String prefixDir)  
  75.             throws IOException, FileNotFoundException {  
  76.         Log.e(TAG, "writeRecursive");  
  77.         ZipEntry zipEntry;  
  78.         String filePath = srcFile.getAbsolutePath().replaceAll("////""/")  
  79.                 .replaceAll("//""/");  
  80.         if (srcFile.isDirectory()) {  
  81.             filePath = filePath.replaceAll("/$""") + "/";  
  82.         }  
  83.         String entryName = filePath.replace(prefixDir, "").replaceAll("/$""");  
  84.         if (srcFile.isDirectory()) {  
  85.             if (!"".equals(entryName)) {  
  86.                 Log.e(TAG, "正在创建目录 - " + srcFile.getAbsolutePath()  
  87.                         + " entryName=" + entryName);  
  88.                 // 如果是目录,则需要在写目录后面加上 /  
  89.                 zipEntry = new ZipEntry(entryName + "/");  
  90.                 zos.putNextEntry(zipEntry);  
  91.             }  
  92.             File srcFiles[] = srcFile.listFiles();  
  93.             for (int i = 0; i < srcFiles.length; i++) {  
  94.                 if (srcFiles[i].isDirectory()  
  95.                         &&  可选指定子目录筛选) {  
  96.                     continue;  
  97.                 }  
  98.                 writeRecursive(zos, bo, srcFiles[i], prefixDir);  
  99.             }  
  100.         } else {  
  101.             Log.e(TAG, "正在写文件 - " + srcFile.getAbsolutePath() + " entryName="  
  102.                     + entryName);  
  103.             BufferedInputStream bi = new BufferedInputStream(  
  104.                     new FileInputStream(srcFile));  
  105.             // 开始写入新的ZIP文件条目并将流定位到条目数据的开始处  
  106.             zipEntry = new ZipEntry(entryName);  
  107.             zos.putNextEntry(zipEntry);  
  108.             byte[] buffer = new byte[1024];  
  109.             int readCount = bi.read(buffer);  
  110.             while (readCount != -1) {  
  111.                 bo.write(buffer, 0, readCount);  
  112.                 readCount = bi.read(buffer);  
  113.             }  
  114.             // 注,在使用缓冲流写压缩文件时,一个条件完后一定要刷新一把,不  
  115.             // 然可能有的内容就会存入到后面条目中去了  
  116.             bo.flush();  
  117.             // 文件读完后关闭  
  118.             bi.close();  
  119.         }  
  120.     }  

 接下来自然是解压缩操作咯:

 

Java代码  收藏代码
  1. /** 
  2.      * [* 使用 org.apache.tools.zip.ZipFile 解压文件,它与 java 类库中的 
  3.      * java.util.zip.ZipFile 使用方式是一新的,只不过多了设置编码方式的 接口。 
  4.      * 注,apache 没有提供 ZipInputStream 类,所以只能使用它提供的ZipFile 来读取压缩文件。]<BR> 
  5.      * @param archive 压缩包路径 
  6.      * @param decompressDir 解压路径 
  7.      * @throws IOException 
  8.      * @throws FileNotFoundException 
  9.      * @throws ZipException 
  10.      */  
  11.     public static void readByApacheZipFile(String archive, String decompressDir)  
  12.             throws IOException, FileNotFoundException, ZipException {  
  13.         Log.e(TAG, "readByApacheZipFile");  
  14.         BufferedInputStream bi;  
  15.         ZipFile zf = new ZipFile(archive, "GBK");// 支持中文  
  16.         Enumeration e = zf.getEntries();  
  17.         while (e.hasMoreElements()) {  
  18.             ZipEntry ze2 = (ZipEntry) e.nextElement();  
  19.             String entryName = ze2.getName();  
  20.             Log.e(TAG, entryName);  
  21.             String path = decompressDir + "/" + entryName;  
  22.             if (ze2.isDirectory()) {  
  23.                 Log.e(TAG, "正在创建解压目录 - " + entryName);  
  24.                 File decompressDirFile = new File(path);  
  25.                 if (!decompressDirFile.exists()) {  
  26.                     decompressDirFile.mkdirs();  
  27.                 }  
  28.             } else {  
  29.                 Log.e(TAG, "正在创建解压文件 - " + entryName);  
  30.                 String fileDir = path.substring(0, path.lastIndexOf("/"));  
  31.                 File fileDirFile = new File(fileDir);  
  32.                 if (!fileDirFile.exists()) {  
  33.                     fileDirFile.mkdirs();  
  34.                 }  
  35.                 BufferedOutputStream bos = new BufferedOutputStream(  
  36.                         new FileOutputStream(decompressDir + "/" + entryName));  
  37.                 bi = new BufferedInputStream(zf.getInputStream(ze2));  
  38.                 byte[] readContent = new byte[1024];  
  39.                 int readCount = bi.read(readContent);  
  40.                 while (readCount != -1) {  
  41.                     bos.write(readContent, 0, readCount);  
  42.                     readCount = bi.read(readContent);  
  43.                 }  
  44.                 bos.close();  
  45.             }  
  46.         }  
  47.         zf.close();  
  48.     }  
  49.   
  50.     /** 
  51.      *  
  52.      * [使用 java api 中的 ZipInputStream 类解压文件,但如果压缩时采用了 
  53.      * org.apache.tools.zip.ZipOutputStream时,而不是 java 类库中的 
  54.      * java.util.zip.ZipOutputStream时,该方法不能使用,原因就是编码方 式不一致导致,运行时会抛如下异常: 
  55.      * java.lang.IllegalArgumentException at 
  56.      * java.util.zip.ZipInputStream.getUTF8String(ZipInputStream.java:290) 
  57.      *  
  58.      * 当然,如果压缩包使用的是java类库的java.util.zip.ZipOutputStream 压缩而成是不会有问题的,但它不支持中文 ]<BR> 
  59.      * [功能详细描述] 
  60.      * @param archive 
  61.      *            压缩包路径 
  62.      * @param decompressDir 
  63.      *            解压路径 
  64.      * @throws FileNotFoundException 
  65.      * @throws IOException 
  66.      * @throws InterruptedException  
  67.      */  
  68.     public static void readByZipInputStream(String archive, String decompressDir)  
  69.             throws FileNotFoundException, IOException{  
  70.         BufferedInputStream bi;  
  71.         // ----解压文件(ZIP文件的解压缩实质上就是从输入流中读取数据):  
  72.         Log.e(TAG, "开始读压缩文件");  
  73.         FileInputStream fi = new FileInputStream(archive);  
  74.         CheckedInputStream csumi = new CheckedInputStream(fi, new CRC32());  
  75.         ZipInputStream in2 = new ZipInputStream(csumi);  
  76.         bi = new BufferedInputStream(in2);  
  77.         java.util.zip.ZipEntry ze;// 压缩文件条目  
  78.         // 遍历压缩包中的文件条目  
  79.         while ((ze = in2.getNextEntry()) != null) {  
  80.             String entryName = ze.getName();  
  81.             Log.e(TAG, "获取到的文件名称 - " + entryName);  
  82.             if (ze.isDirectory()) {  
  83.                 entryName = entryName.replace("/""");  
  84.                 Log.e(TAG, "正在创建解压目录 - " + entryName);  
  85.                 File decompressDirFile = new File(decompressDir + "/"  
  86.                         + entryName);  
  87.                 if (!decompressDirFile.exists()) {  
  88.                     decompressDirFile.mkdirs();  
  89.                     ShellUtils.updateChmod(decompressDir + "/" + entryName);  
  90.                     try {  
  91.                         Thread.sleep(600);  
  92.                     } catch (InterruptedException e) {  
  93.                         // TODO Auto-generated catch block  
  94.                         e.printStackTrace();  
  95.                     }  
  96.                 }  
  97.             } else {  
  98.                 String fileName = decompressDir + "/" + entryName;  
  99.                 Log.e(TAG, "正在创建解压文件 - " + fileName);  
  100.                 BufferedOutputStream bos = new BufferedOutputStream(  
  101.                         new FileOutputStream(fileName));  
  102.                 byte[] buffer = new byte[1024 * 5];  
  103.                 int readCount = bi.read(buffer);  
  104.                 while (readCount != -1) {  
  105.                     bos.write(buffer, 0, readCount);  
  106.                     readCount = bi.read(buffer);  
  107.                 }  
  108.                 bos.close();  
  109.                 ShellUtils.updateChmod(fileName);  
  110.                 ExtraHelpUtils.threadSleep(200);  
  111.             }  
  112.         }  
  113.         bi.close();  
  114.     }  

 好了,至于调用方法,此处就不多做说明了。。很简单的



原创粉丝点击