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

包自己导入一下就行了

相关推荐
cike_y1 天前
JSP内置对象及作用域&双亲委派机制
java·前端·网络安全·jsp·安全开发
也许是_1 天前
大模型应用技术之 Spring AI 2.0 变更说明
java·人工智能·spring
xunyan62341 天前
面向对象(下)-内部类的分类
java·学习
Insight.1 天前
背包问题——01背包、完全背包、多重背包、分组背包(Python)
开发语言·python
巴拉巴拉~~1 天前
KMP 算法通用进度条组件:KmpProgressWidget 多维度 + 匹配进度联动 + 平滑动画
java·服务器·前端
aini_lovee1 天前
改进遗传算法求解VRP问题时的局部搜索能力
开发语言·算法·matlab
Yeniden1 天前
Deepeek用大白话讲解 --> 迭代器模式(企业级场景1,多种遍历方式2,隐藏集合结构3,Java集合框架4)
java·开发语言·迭代器模式
SmoothSailingT1 天前
C#——LINQ方法
开发语言·c#·linq
景川呀1 天前
Java的类加载器
java·开发语言·java类加载器
yaoxin5211231 天前
274. Java Stream API - 过滤操作(filter):筛选你想要的数据
java·windows