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

包自己导入一下就行了

相关推荐
用户1616865754930几秒前
Spring Boot动态数据源切换:优雅实现多数据源管理
java
法的空间3 分钟前
JsonToDart,你已经是一个成熟的工具了,接下来就靠你自己继续进化了!
android·flutter·ios
喵手4 分钟前
DateUtils 和 LocalDateTime 工具类:日期时间的优雅处理!
java·后端·java ee
玲小珑4 分钟前
Auto.js 入门指南(十八)常见问题与解决方案
android·前端
喵手6 分钟前
如何优雅封装统一日志打印工具类?一文教会你!
java·后端·java ee
鸽鸽程序猿7 分钟前
【算法】【优选算法】优先级队列
java·算法
hello早上好7 分钟前
Spring作用域与生命周期
java·后端·架构
三少爷的鞋12 分钟前
Kotlin 协程合理管理协程作用域:从 CoroutineScope 到 suspend 函数的重构实践
android
锋风16 分钟前
安卓对外发布工程源码:怎么做到仅UI层公布
android
桦说编程20 分钟前
并发编程与视图——简单方法返回异步 Map<Key, Data>
java·设计模式