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/");

包自己导入一下就行了

相关推荐
人活一口气10 小时前
Spring Boot与AIGC的完美结合:从零搭建智能内容生成平台
java·spring boot·aigc
像我这样帅的人丶你还12 小时前
Java 后端详解(三):全局异常处理与 JPA 数据库映射
java·后端
NE_STOP12 小时前
vibe Coding -- 小项目实战
java
未秃头的程序猿18 小时前
Java 26正式发布!这3个新特性,让代码量直接减半
java·后端·面试
37手游移动客户端团队18 小时前
招聘-高级安卓开发工程师
android·客户端
用户2986985301418 小时前
Word 文档文本查找与替换的 Java 实现方案
java·后端
阿哉18 小时前
Nacos 服务发现源码:藏在背后的两套事件机制,90%的人只讲了一半
java
用户416596736935518 小时前
WebView 请求异常排查操作手册
android·前端
咖啡八杯19 小时前
GoF设计模式——命令模式
java·设计模式·架构
AI人工智能_电脑小能手19 小时前
【大白话说Java面试题 第125题】【并发篇】第25题:说说 Java 线程的中断机制
java·后端·面试