android 进行多文件压缩处理格式zip

下面的小代码为周未时间所写。主要利用了ant.jar对文件进行压缩处理。以下为全部代码,界面是随便所画。如有什么问题还希望各位指出。

xml文件代码 :

[xhtml] view plain copy
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:orientation="vertical"  
  4.     android:layout_width="fill_parent"  
  5.     android:layout_height="fill_parent"  
  6.     >  
  7. <TextView    
  8.     android:layout_width="fill_parent"   
  9.     android:layout_height="wrap_content"   
  10.     android:text="@string/hello"  
  11.     />  
  12.     <Button android:layout_width="wrap_content"  
  13.         android:layout_height="wrap_content" android:id="@+id/backup"  
  14.         android:text="backup" />  
  15.     <Button android:layout_width="wrap_content"  
  16.         android:layout_height="wrap_content" android:id="@+id/recover"  
  17.         android:text="recover"/>  
  18. </LinearLayout>  

android 代码:

  1. package com.android.file;  
  2.   
  3. import java.io.File;  
  4. import java.io.FileNotFoundException;  
  5. import java.io.IOException;  
  6. import java.util.zip.ZipException;  
  7.   
  8. import com.android.file.zip.ZipControl;  
  9.   
  10. import android.app.Activity;  
  11. import android.os.Bundle;  
  12. import android.util.Log;  
  13. import android.view.View;  
  14. import android.view.View.OnClickListener;  
  15. import android.widget.Button;  
  16.   
  17. public class FileAndroidActivity extends Activity implements OnClickListener {  
  18.     private final static  String TAG = "FileAndroidActivity";  
  19.     private String[] fileSrcStrings;//指定压缩源,可以是目录或文件的数组  
  20.     private String decompressDirString="";//解压路径  
  21.     private String archiveString="";//压缩包路径  
  22.     private String commentString="Androi Java Zip 测试.";//压缩包注释  
  23.     private ZipControl mZipControl;  
  24.     private Button mBackupButton;  
  25.     private Button mRecoverButton;  
  26.     private String srcString;//第一个文件的路径  
  27.     private String srcTwoString;//第二个文件的路径  
  28.     /** Called when the activity is first created. */  
  29.     @Override  
  30.     public void onCreate(Bundle savedInstanceState) {  
  31.         super.onCreate(savedInstanceState);  
  32.         setContentView(R.layout.main);  
  33.         mBackupButton = (Button) findViewById(R.id.backup);  
  34.         mRecoverButton = (Button) findViewById(R.id.recover);  
  35.         mBackupButton.setOnClickListener(this);  
  36.         mRecoverButton.setOnClickListener(this);  
  37.         String pathString =this.getCacheDir().toString();  
  38.         Log.e(TAG, "path is "+ pathString);  
  39.         archiveString=pathString+"/zip";  
  40.         decompressDirString = pathString+"/unzip";  
  41.         File zipFile = new File(archiveString);  
  42.         if(!zipFile.exists())  
  43.         {  
  44.           zipFile.mkdir();  
  45.           Log.e(TAG, "make zipdir success");  
  46.         }  
  47.         else {  
  48.             Log.e(TAG, "exit zipdir");  
  49.         }  
  50.         File unZipFile = new File(decompressDirString);  
  51.         if(!unZipFile.exists())  
  52.         {  
  53.             unZipFile.mkdir();  
  54.             Log.e(TAG, "make undir success");  
  55.         }  
  56.         else  
  57.         {  
  58.             Log.e(TAG, "exit undir");  
  59.         }  
  60.         String strFileOne = pathString+"/fileoneDir";  
  61.         File fileOneFile = new File(strFileOne);  
  62.         if(!fileOneFile.exists())  
  63.         {  
  64.             fileOneFile.mkdir();  
  65.             Log.e(TAG, "make fileonedir success");  
  66.         }  
  67.         else {  
  68.             Log.e(TAG, "exit fileonedir");  
  69.         }  
  70.         srcString = strFileOne+"/testfile01.txt";  
  71.         String strFileTwo =pathString+"/filetwoDir";  
  72.         File fileOneFileTwo = new File(strFileTwo);  
  73.         if(!fileOneFileTwo.exists())  
  74.         {  
  75.             fileOneFileTwo.mkdir();  
  76.             Log.e(TAG, "make filetwoDir success");  
  77.         }  
  78.         else {  
  79.             Log.e(TAG, "exit filetwoDir");  
  80.         }  
  81.         srcTwoString = strFileTwo+"/testfile02.txt";  
  82.         fileSrcStrings= new String[]{srcString,srcTwoString};  
  83.         mZipControl = new ZipControl();  
  84.     }  
  85.     @Override  
  86.     public void onClick(View v)  
  87.     {  
  88.         int id = v.getId();  
  89.         switch (id)  
  90.         {  
  91.             case R.id.backup:  
  92.                 Log.e(TAG, "start backup");  
  93.                 try  
  94.                 {  
  95.                     mZipControl.writeByApacheZipOutputStream(fileSrcStrings, archiveString+"/test.zip", commentString);  
  96.                 }  
  97.                 catch (FileNotFoundException e)  
  98.                 {  
  99.                     Log.e(TAG, e.toString());  
  100.                     // TODO Auto-generated catch block  
  101.                     e.printStackTrace();  
  102.                 }  
  103.                 catch (IOException e)  
  104.                 {  
  105.                     Log.e(TAG, e.toString());  
  106.                     // TODO Auto-generated catch block  
  107.                     e.printStackTrace();  
  108.                 }  
  109.                 break;  
  110.             case R.id.recover:  
  111.                 try  
  112.                 {  
  113.                     ZipControl.readByApacheZipFile(archiveString+"/test.zip", decompressDirString);  
  114.                 }  
  115.                 catch (FileNotFoundException e)  
  116.                 {  
  117.                     Log.e(TAG, e.toString());  
  118.                     // TODO Auto-generated catch block  
  119.                     e.printStackTrace();  
  120.                 }  
  121.                 catch (ZipException e)  
  122.                 {  
  123.                     Log.e(TAG, e.toString());  
  124.                     // TODO Auto-generated catch block  
  125.                     e.printStackTrace();  
  126.                 }  
  127.                 catch (IOException e)  
  128.                 {  
  129.                     // TODO Auto-generated catch block  
  130.                     e.printStackTrace();  
  131.                 }  
  132.                 Log.e(TAG, "start recover ");  
  133.                 break;  
  134.             default:  
  135.                 break;  
  136.         }  
  137.     }  
  138. }  

对文件压缩的主要代码类:

  1. package com.android.file.zip;  
  2.   
  3. import java.io.BufferedInputStream;  
  4. import java.io.BufferedOutputStream;  
  5. import java.io.File;  
  6. import java.io.FileInputStream;  
  7. import java.io.FileNotFoundException;  
  8. import java.io.FileOutputStream;  
  9. import java.io.IOException;  
  10. import java.util.Enumeration;  
  11. import java.util.zip.CRC32;  
  12. import java.util.zip.CheckedInputStream;  
  13. import java.util.zip.CheckedOutputStream;  
  14. import java.util.zip.Deflater;  
  15. import java.util.zip.ZipException;  
  16. import java.util.zip.ZipInputStream;  
  17. import org.apache.tools.zip.ZipEntry;  
  18. import org.apache.tools.zip.ZipFile;  
  19. import org.apache.tools.zip.ZipOutputStream;  
  20.   
  21. import android.util.Log;  
  22. /** 
  23.  *  
  24.  * [一句话功能简述]<BR> 
  25.  * [功能详细描述] 
  26.  * @author zhouxin 
  27.  * @version [Android MTVClient C01, 2011-3-4] 
  28.  */  
  29. public class ZipControl  
  30. {  
  31.     private static boolean isCreateSrcDir = false;//是否创建源目录 在这里的话需要说明下。如果需要创建源目录的话。就在这里设为true否则为false;  
  32.     private static String TAG="ZipControl";  
  33.     /** 
  34.      *  
  35.      * [对指定路径下文件的压缩处理]<BR> 
  36.      * [功能详细描述] 
  37.      *  
  38.      * @param src 径地址 
  39.      * @param archive 指定到压缩文件夹的路径 
  40.      * @param comment 描述 
  41.      * @throws FileNotFoundException 文件没有找到异常 
  42.      * @throws IOException IO输入异常 
  43.      */  
  44.     public  void writeByApacheZipOutputStream(String[] src,  
  45.         String archive, String comment) throws FileNotFoundException,  
  46.         IOException  
  47.     {  
  48.         Log.e(TAG, "writeByApacheZipOutputStream");  
  49.         //----压缩文件:  
  50.         FileOutputStream f = new FileOutputStream(archive);  
  51.         //使用指定校验和创建输出流  
  52.         CheckedOutputStream csum = new CheckedOutputStream(f, new CRC32());  
  53.         ZipOutputStream zos = new ZipOutputStream(csum);  
  54.         //支持中文  
  55.         zos.setEncoding("GBK");  
  56.         BufferedOutputStream out = new BufferedOutputStream(zos);  
  57.         //设置压缩包注释  
  58.         zos.setComment(comment);  
  59.         //启用压缩  
  60.         zos.setMethod(ZipOutputStream.DEFLATED);  
  61.         //压缩级别为最强压缩,但时间要花得多一点  
  62.         zos.setLevel(Deflater.BEST_COMPRESSION);  
  63.         // 如果为单个文件的压缩在这里修改  
  64.         for (int i = 0; i < src.length; i++)  
  65.         {  
  66.             Log.e(TAG, "src["+i+"] is "+src[i]);  
  67.             File srcFile = new File(src[i]);  
  68.             if (!srcFile.exists()  
  69.                 || (srcFile.isDirectory() && srcFile.list().length == 0))  
  70.             {  
  71.                 Log.e(TAG, "!srcFile.exists()");  
  72.                 throw new FileNotFoundException(  
  73.                     "File must exist and ZIP file must have at least one entry.");  
  74.             }  
  75.             String strSrcString = src[i];  
  76.             //获取压缩源所在父目录  
  77.             strSrcString = strSrcString.replaceAll("""/");  
  78.             String prefixDir = null;  
  79.             if (srcFile.isFile())  
  80.             {  
  81.                 prefixDir = strSrcString.substring(0, strSrcString  
  82.                     .lastIndexOf("/") + 1);  
  83.             }  
  84.             else  
  85.             {  
  86.                 prefixDir = (strSrcString.replaceAll("/$""") + "/");  
  87.             }  
  88.             //如果不是根目录  
  89.             if (prefixDir.indexOf("/") != (prefixDir.length() - 1)  
  90.                 && isCreateSrcDir)  
  91.             {  
  92.                 prefixDir = prefixDir.replaceAll("[^/]+/$""");  
  93.             }  
  94.             //开始压缩  
  95.             writeRecursive(zos, out, srcFile, prefixDir);  
  96.         }  
  97.   
  98.         out.close();  
  99.         // 注:校验和要在流关闭后才准备,一定要放在流被关闭后使用  
  100.         Log.e(TAG, "Checksum: " + csum.getChecksum().getValue());  
  101.         @SuppressWarnings("unused")  
  102.         BufferedInputStream bi;  
  103.     }  
  104.     /** 
  105.      *  
  106.      * [* 使用 org.apache.tools.zip.ZipFile 解压文件,它与 java 类库中的 
  107.      * java.util.zip.ZipFile 使用方式是一新的,只不过多了设置编码方式的 接口。 
  108.      *  
  109.      * 注,apache 没有提供 ZipInputStream 类,所以只能使用它提供的ZipFile 来读取压缩文件。]<BR> 
  110.      *  
  111.      * @param archive 压缩包路径 
  112.      * @param decompressDir 解压路径 
  113.      * @throws IOException 
  114.      * @throws FileNotFoundException 
  115.      * @throws ZipException 
  116.      */  
  117.   
  118.     @SuppressWarnings("unchecked")  
  119.     public static void readByApacheZipFile(String archive, String decompressDir)  
  120.         throws IOException, FileNotFoundException, ZipException  
  121.     {  
  122.         Log.e(TAG, "readByApacheZipFile");  
  123.         BufferedInputStream bi;  
  124.         ZipFile zf = new ZipFile(archive, "GBK");//支持中文  
  125.         Enumeration e = zf.getEntries();  
  126.         while (e.hasMoreElements())  
  127.         {  
  128.             ZipEntry ze2 = (ZipEntry) e.nextElement();  
  129.             String entryName = ze2.getName();  
  130.             String path = decompressDir + "/" + entryName;  
  131.             if (ze2.isDirectory())  
  132.             {  
  133.                 Log.e(TAG, "正在创建解压目录 - " + entryName);  
  134.                 File decompressDirFile = new File(path);  
  135.                 if (!decompressDirFile.exists())  
  136.                 {  
  137.                     decompressDirFile.mkdirs();  
  138.                 }  
  139.             }  
  140.             else  
  141.             {  
  142.                 Log.e(TAG, "正在创建解压文件 - " + entryName);  
  143.                 String fileDir = path.substring(0, path.lastIndexOf("/"));  
  144.                 File fileDirFile = new File(fileDir);  
  145.                 if (!fileDirFile.exists())  
  146.                 {  
  147.                     fileDirFile.mkdirs();  
  148.                 }  
  149.                 BufferedOutputStream bos = new BufferedOutputStream(  
  150.                     new FileOutputStream(decompressDir + "/" + entryName));  
  151.                 bi = new BufferedInputStream(zf.getInputStream(ze2));  
  152.                 byte[] readContent = new byte[1024];  
  153.                 int readCount = bi.read(readContent);  
  154.                 while (readCount != -1)  
  155.                 {  
  156.                     bos.write(readContent, 0, readCount);  
  157.                     readCount = bi.read(readContent);  
  158.                 }  
  159.                 bos.close();  
  160.             }  
  161.         }  
  162.         zf.close();  
  163.     }  
  164.     /** 
  165.      *  
  166.      * [使用 java api 中的 ZipInputStream 类解压文件,但如果压缩时采用了 
  167.      * org.apache.tools.zip.ZipOutputStream时,而不是 java 类库中的 
  168.      * java.util.zip.ZipOutputStream时,该方法不能使用,原因就是编码方 式不一致导致,运行时会抛如下异常: 
  169.      * java.lang.IllegalArgumentException at 
  170.      * java.util.zip.ZipInputStream.getUTF8String(ZipInputStream.java:290) 
  171.      *  
  172.      * 当然,如果压缩包使用的是java类库的java.util.zip.ZipOutputStream 压缩而成是不会有问题的,但它不支持中文 ]<BR> 
  173.      * [功能详细描述] 
  174.      *  
  175.      * @param archive 压缩包路径 
  176.      * @param decompressDir 解压路径 
  177.      * @throws FileNotFoundException 
  178.      * @throws IOException 
  179.      */  
  180.     public static void readByZipInputStream(String archive, String decompressDir)  
  181.         throws FileNotFoundException, IOException  
  182.     {  
  183.         BufferedInputStream bi;  
  184.         //----解压文件(ZIP文件的解压缩实质上就是从输入流中读取数据):  
  185.         Log.e(TAG, "开始读压缩文件");  
  186.         FileInputStream fi = new FileInputStream(archive);  
  187.         CheckedInputStream csumi = new CheckedInputStream(fi, new CRC32());  
  188.         ZipInputStream in2 = new ZipInputStream(csumi);  
  189.         bi = new BufferedInputStream(in2);  
  190.         java.util.zip.ZipEntry ze;//压缩文件条目  
  191.         //遍历压缩包中的文件条目  
  192.         while ((ze = in2.getNextEntry()) != null)  
  193.         {  
  194.             String entryName = ze.getName();  
  195.             if (ze.isDirectory())  
  196.             {  
  197.                 Log.e(TAG,"正在创建解压目录 - " + entryName);  
  198.                 File decompressDirFile = new File(decompressDir + "/"  
  199.                     + entryName);  
  200.                 if (!decompressDirFile.exists())  
  201.                 {  
  202.                     decompressDirFile.mkdirs();  
  203.                 }  
  204.             }  
  205.             else  
  206.             {  
  207.                 Log.e(TAG, "正在创建解压文件 - " + entryName);  
  208.                 BufferedOutputStream bos = new BufferedOutputStream(  
  209.                     new FileOutputStream(decompressDir  
  210.                         + "/"  
  211.                         + entryName.substring(entryName.lastIndexOf("//"),  
  212.                             entryName.length()  
  213.                                 - (entryName.lastIndexOf("//") - 2))));  
  214.                 byte[] buffer = new byte[1024];  
  215.                 int readCount = bi.read(buffer);  
  216.                 while (readCount != -1)  
  217.                 {  
  218.                     bos.write(buffer, 0, readCount);  
  219.                     readCount = bi.read(buffer);  
  220.                 }  
  221.                 bos.close();  
  222.             }  
  223.         }  
  224.         bi.close();  
  225.         Log.e(TAG, "Checksum: " + csumi.getChecksum().getValue());  
  226.     }  
  227.   
  228.     /** 
  229.      *  
  230.      * [递归压缩 
  231.      *  
  232.      * 使用 org.apache.tools.zip.ZipOutputStream 类进行压缩,它的好处就是支持中文路径, 而Java类库中的 
  233.      * java.util.zip.ZipOutputStream 压缩中文文件名时压缩包会出现乱码。 使用 apache 中的这个类与 java 
  234.      * 类库中的用法是一新的,只是能设置编码方式了。]<BR> 
  235.      * [功能详细描述] 
  236.      *  
  237.      * @param zos 
  238.      * @param bo 
  239.      * @param srcFile 
  240.      * @param prefixDir 
  241.      * @throws IOException 
  242.      * @throws FileNotFoundException 
  243.      */  
  244.     private static void writeRecursive(ZipOutputStream zos,  
  245.         BufferedOutputStream bo, File srcFile, String prefixDir)  
  246.         throws IOException, FileNotFoundException  
  247.     {  
  248.         Log.e(TAG, "writeRecursive");  
  249.         ZipEntry zipEntry;  
  250.         String filePath = srcFile.getAbsolutePath().replaceAll("""/")  
  251.             .replaceAll("//""/");  
  252.         if (srcFile.isDirectory())  
  253.         {  
  254.             filePath = filePath.replaceAll("/$""") + "/";  
  255.         }  
  256.         String entryName = filePath.replace(prefixDir, "").replaceAll("/$""");  
  257.         if (srcFile.isDirectory())  
  258.         {  
  259.             if (!"".equals(entryName))  
  260.             {  
  261.                 Log.e(TAG, "正在创建目录 - " + srcFile.getAbsolutePath()  
  262.                     + " entryName=" + entryName);  
  263.                 //如果是目录,则需要在写目录后面加上 /  
  264.                 zipEntry = new ZipEntry(entryName + "/");  
  265.                 zos.putNextEntry(zipEntry);  
  266.             }  
  267.             File srcFiles[] = srcFile.listFiles();  
  268.             for (int i = 0; i < srcFiles.length; i++)  
  269.             {  
  270.                 writeRecursive(zos, bo, srcFiles[i], prefixDir);  
  271.             }  
  272.         }  
  273.         else  
  274.         {  
  275.             Log.e(TAG,"正在写文件 - " + srcFile.getAbsolutePath()  
  276.                 + " entryName=" + entryName );  
  277.             BufferedInputStream bi = new BufferedInputStream(  
  278.                 new FileInputStream(srcFile));  
  279.             //开始写入新的ZIP文件条目并将流定位到条目数据的开始处  
  280.             zipEntry = new ZipEntry(entryName);  
  281.             zos.putNextEntry(zipEntry);  
  282.             byte[] buffer = new byte[1024];  
  283.             int readCount = bi.read(buffer);  
  284.             while (readCount != -1)  
  285.             {  
  286.                 bo.write(buffer, 0, readCount);  
  287.                 readCount = bi.read(buffer);  
  288.             }  
  289.             //注,在使用缓冲流写压缩文件时,一个条件完后一定要刷新一把,不  
  290.             //然可能有的内容就会存入到后面条目中去了  
  291.             bo.flush();  
  292.             //文件读完后关闭  
  293.             bi.close();  
  294.         }  
  295.     }  

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值