Android 解压zip压缩包 (压缩包内有多级目录)

目录

一、AndroidManifest.xml 添加 sd 卡读写权限

二、具体使用方法

注记:


我们需要同时下载多个文件时,一般是使用压缩包来实现。

一、AndroidManifest.xml 添加 sd 卡读写权限

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

二、具体使用方法

/**
     * @param zipFile zip压缩包路径
     * @param folderPath 解压文件存放路径
     */
    public void unzipFile(String zipFile, String folderPath) {
        try {
            ZipFile zfile = null;
            // 转码为GBK格式,支持中文
            zfile = new ZipFile(zipFile);
            Enumeration zList = zfile.entries();
            ZipEntry ze = null;
            byte[] buf = new byte[1024 * 1024];
            while (zList.hasMoreElements()) {
                ze = (ZipEntry) zList.nextElement();
                // 列举的压缩文件里面的各个文件,判断是否为目录
                if (ze.isDirectory()) {
                    String dirstr = folderPath + ze.getName();
                    dirstr.trim();
                    File f = new File(dirstr);
                    f.mkdir();
                    continue;
                }
                OutputStream os = null;
                FileOutputStream fos = null;
                // ze.getName()会返回 script/start.script这样的,是为了返回实体的File
                File realFile = getRealFileName(folderPath, ze.getName());
                fos = new FileOutputStream(realFile);
                os = new BufferedOutputStream(fos);
                InputStream is = null;
                is = new BufferedInputStream(zfile.getInputStream(ze));
                int readLen = 0;
                // 进行一些内容复制操作
                while ((readLen = is.read(buf, 0, 1024)) != -1) {
                    os.write(buf, 0, readLen);
                }
                is.close();
                os.close();
            }
            zfile.close();

            //解压完成后,删除压缩包文件(此处根据需要可进行删除)
            File file = new File(zipFile);
            file.delete();

            Toast.makeText(MyActivity.this, "解压成功!", Toast.LENGTH_LONG).show();
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(MyActivity.this, "解压失败!", Toast.LENGTH_LONG).show();
        }
    }

此方法亲测可以解压多级目录的压缩包,但是也有一个问题。压缩包内的空文件夹,解压之后的该文件就不存在了(该bug在我当前使用的项目中无影响,暂未修改)。

注记:

压缩包内的空文件在解压后不存在的修改思路:

Enumeration zList = zfile.entries();
ZipEntry ze = (ZipEntry) zList.nextElement();

当 ze.getSize() 不在大于 0 时,此时就是空文件夹,使用 ze.getName() 可获取空文件夹名,然后我们再去相应的路径下去创建它就OK了。

猜你喜欢

转载自blog.csdn.net/minusn/article/details/126241641
今日推荐