Android SD卡中压缩包解压(ZIP文件)

  1 package com.zip.file;
2 /**
3 * @author wainiwann
4 * 仅限解压ZIP压缩文件 并且不支持压缩文件内包含子目录的情况
5 */
6 import java.io.File;
7 import java.io.FileOutputStream;
8 import java.io.IOException;
9 import java.io.InputStream;
10 import java.io.OutputStream;
11 import java.util.Enumeration;
12 import java.util.zip.ZipEntry;
13 import java.util.zip.ZipException;
14 import java.util.zip.ZipFile;
15
16 import android.app.Activity;
17 import android.os.Bundle;
18 import android.util.Log;
19 import android.view.View;
20 import android.view.View.OnClickListener;
21 import android.widget.Button;
22
23 public class CopyOfZipFile_备份 extends Activity
24 {
25 private Button m_btn = null;
26 private final static String FROMPATH = "/mnt/sdcard/zipFile.zip";
27 private final static String TOPATH = "/mnt/sdcard/B/ZIP/";
28 File zipFile ;
29 /** Called when the activity is first created. */
30 @Override
31 public void onCreate(Bundle savedInstanceState)
32 {
33 super.onCreate(savedInstanceState);
34 setContentView(R.layout.main);
35
36
37 m_btn = (Button) findViewById(R.id.button1);
38 zipFile = new File(FROMPATH);
39 m_btn.setOnClickListener(new OnClickListener()
40 {
41
42 @Override
43 public void onClick(View v)
44 {
45 // TODO Auto-generated method stub
46 try {
47 upZipFile(zipFile,TOPATH);
48 } catch (ZipException e) {
49 // TODO Auto-generated catch block
50 e.printStackTrace();
51 } catch (IOException e) {
52 // TODO Auto-generated catch block
53 e.printStackTrace();
54 }
55 }
56
57 });
58 }
59
60
61 /**
62 * 解压缩一个文件
63 *
64 * @param zipFile 要解压的压缩文件
65 * @param folderPath 解压缩的目标目录
66 * @throws IOException 当解压缩过程出错时抛出
67 */
68 public void upZipFile(File zipFile, String folderPath) throws ZipException, IOException
69 {
70 File desDir = new File(folderPath);
71 if(!desDir.exists())
72 {
73 desDir.mkdirs();
74 }
75
76 ZipFile zf = new ZipFile(zipFile);
77 for (Enumeration<?> entries = zf.entries(); entries.hasMoreElements();)
78 {
79 ZipEntry entry = ((ZipEntry)entries.nextElement());
80 InputStream in = zf.getInputStream(entry);
81 String str = folderPath + File.separator + entry.getName();
82 str = new String(str.getBytes("8859_1"), "GB2312");
83 File desFile = new File(str);
84 if (!desFile.exists())
85 {
86 File fileParentDir = desFile.getParentFile();
87 if (!fileParentDir.exists())
88 {
89 fileParentDir.mkdirs();
90 }
91 desFile.createNewFile();
92 }
93 OutputStream out = new FileOutputStream(desFile);
94 byte buffer[] = new byte[1024];
95 int realLength;
96 while ((realLength = in.read(buffer)) > 0)
97 {
98 out.write(buffer, 0, realLength);
99 }
100 in.close();
101 out.close();
102 }
103 }
104
105
106 }

需要添加权限在AndriodManifest.xml里:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>

参考博客:http://www.oschina.net/code/snippet_4873_4142

原文地址:https://www.cnblogs.com/wainiwann/p/2340478.html