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

包自己导入一下就行了

相关推荐
阿湯哥14 分钟前
Spring AI Alibaba 实现 Workflow 全指南
java·人工智能·spring
方白羽26 分钟前
Android 开发中,准确判断应用处于“前台(Foreground)”还是“后台(Background)
android·app·客户端
星竹晨L34 分钟前
【C++内存安全管理】智能指针的使用和原理
开发语言·c++
宵时待雨35 分钟前
数据结构(初阶)笔记归纳3:顺序表的应用
c语言·开发语言·数据结构·笔记·算法
旺仔小拳头..42 分钟前
Java ---变量、常量、类型转换、默认值、重载、标识符、输入输出、访问修饰符、泛型、迭代器
java·开发语言·python
12344521 小时前
【面试复盘】有了equals为什么还要hashcode
java·后端
lsx2024061 小时前
Vue3 自定义指令
开发语言
牛奔1 小时前
Go语言中结构体转Map优雅实现
开发语言·后端·macos·golang·xcode
毕设源码-邱学长1 小时前
【开题答辩全过程】以 台球俱乐部管理系统为例,包含答辩的问题和答案
java·eclipse
wujj_whut1 小时前
【Conda实战】从0到1:虚拟环境创建、多Python版本管理与环境切换全指南
开发语言·python·conda