Android Zip文件解压代码

来源:互联网 发布:a5源码网 编辑:程序博客网 时间:2024/05/21 09:15

http://blog.csdn.net/jxy1197/article/details/8448694

我们在日常生活中会用到解压缩,这个是非常重要的,那么我们在android系统中有没有解压缩那。如果有的话,那我们如何实现Zip文件的解压缩功能呢? 那么我们就看看下面的解析吧,因为Android内部已经集成了zlib库,对于英文和非密码的Zip文件解压缩还是比较简单的,下面给大家一个解压缩zip的java代码,可以在Android上任何版本中使用,Unzip这个静态方法比较简单,参数一为源zip文件的完整路径,参数二为解压缩后存放的文件夹。希望这段代码能教会大家解压缩。


private static void Unzip(String zipFile, String targetDir) {
int BUFFER = 4096; //这里缓冲区我们使用4KB,
String strEntry; //保存每个zip的条目名称

try {
BufferedOutputStream dest = null; //缓冲输出流
FileInputStream fis = new FileInputStream(zipFile);
ZipInputStream zis = new ZipInputStream(new BufferedInputStream(fis));
ZipEntry entry; //每个zip条目的实例


while ((entry = zis.getNextEntry()) != null) {


try {
Log.i("Unzip: ","="+ entry);
int count; 
byte data[] = new byte[BUFFER];
strEntry = entry.getName();


File entryFile = new File(targetDir + strEntry);
File entryDir = new File(entryFile.getParent());
if (!entryDir.exists()) {
entryDir.mkdirs();
}


FileOutputStream fos = new FileOutputStream(entryFile);
dest = new BufferedOutputStream(fos, BUFFER);
while ((count = zis.read(data, 0, BUFFER)) != -1) {
dest.write(data, 0, count);
}
dest.flush();
dest.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
zis.close();
} catch (Exception cwj) {
cwj.printStackTrace();
}
}


上面是Android开发网总结的zip文件解压缩代码,希望你大家有用,需要注意的是参数均填写完整的路径,比如/mnt/sdcard/xxx.zip这样的类型。


下面的方法是,解压只有一个文件组成的zip到当前目录,并且给解压出的文件重命名:


public static void unzipSingleFileHereWithFileName(String zipPath, String name) throws IOException{
        File zipFile = new File(zipPath);
        File unzipFile = new File(zipFile.getParent() + "/" + name);
        ZipInputStream zipInStream = null;
        FileOutputStream unzipOutStream = null;
        try {
            zipInStream = new ZipInputStream(new FileInputStream(zipFile));
            ZipEntry zipEntry = zipInStream.getNextEntry();
            if (!zipEntry.isDirectory()) {
                unzipOutStream = new FileOutputStream(unzipFile);
                byte[] buf = new byte[4096];
                int len = -1;
                while((len = zipInStream.read(buf)) != -1){
                    unzipOutStream.write(buf, 0, len);
                }
            }
        } finally {
            if(unzipOutStream != null){
                unzipOutStream.close();
            }


            if (zipInStream != null) {
               zipInStream.close();
            }
        }
    }

0 0
原创粉丝点击