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

包自己导入一下就行了

相关推荐
GodSure09149 分钟前
Java单一职责原则SRP详解
java·python·单一职责原则
探数API小喇叭13 分钟前
基站查询 API 怎么用?LAC、CELLID 参数详解与实战】
java·开发语言·api·基站定位
catino14 分钟前
spring-IOC、DI
java·spring·rpc
Mr.Lu ‍16 分钟前
C++开发,使用openCV API对图片进行压缩
开发语言·c++·opencv
z落落17 分钟前
C# WinForm NModbus 串口通信+WinForm Modbus4 串口通信
开发语言·单片机·c#
Mojitocean19 分钟前
Win开发环境配置(持续更新)
开发语言·python
CoderIsArt41 分钟前
C#环境中部署MQTT客户端
开发语言·c#