Android解压zip文件到指定目录

很多时候需要把一个预制的zip文件解压到根目录,下面是一个实例代码:

复制代码
	private static final int BUFFER_SIZE = 4096;

    public static void unZip(String zipFilePath, String targetDir) throws IOException {
        File destDir = new File(targetDir);
        if (!destDir.exists()) {
            destDir.mkdirs();
        }

        try (FileInputStream fis = new FileInputStream(zipFilePath);
             ZipInputStream zis = new ZipInputStream(new BufferedInputStream(fis))) {

            ZipEntry entry;
            while ((entry = zis.getNextEntry()) != null) {
                String entryName = entry.getName();
                File file = new File(destDir, entryName);

                if (entry.isDirectory()) {
                    file.mkdirs();
                } else {
                    extractFile(zis, file);
                }
                zis.closeEntry();
            }
        }
    }

    private static void extractFile(ZipInputStream zis, File file) throws IOException {
        File parent = file.getParentFile();
        if (!parent.exists()) {
            parent.mkdirs();
        }

        try (FileOutputStream fos = new FileOutputStream(file);
             BufferedOutputStream bos = new BufferedOutputStream(fos, BUFFER_SIZE)) {

            byte[] buffer = new byte[BUFFER_SIZE];
            int read;
            while ((read = zis.read(buffer)) != -1) {
                bos.write(buffer, 0, read);
            }
        }
    }

使用实例:

unZip("/system/media/xxx.zip", "/storage/emulated/0/");

包自己导入一下就行了

相关推荐
_一条咸鱼_1 小时前
揭秘 Android TextInputLayout:从源码深度剖析其使用原理
android·java·面试
_一条咸鱼_1 小时前
揭秘!Android VideoView 使用原理大起底
android·java·面试
_一条咸鱼_1 小时前
深度揭秘!Android TextView 使用原理全解析
android·java·面试
游离状态的猫11 小时前
JavaScript性能优化实战:从瓶颈定位到极致提速
开发语言·javascript·性能优化
GeekABC1 小时前
FastAPI系列06:FastAPI响应(Response)
开发语言·python·fastapi·web
小彭努力中1 小时前
7.Three.js 中 CubeCamera详解与实战示例
开发语言·前端·javascript·vue.js·ecmascript
_一条咸鱼_1 小时前
深度剖析:Android Canvas 使用原理全揭秘
android·java·面试
_一条咸鱼_1 小时前
深度剖析!Android TextureView 使用原理全揭秘
android·java·面试