解压zip文件到指定目录

代码很简单,但要注意解压的时候排除__MACOSX目录

/**
     * 解压zip文件到指定目录
     * unzip(new File("1.zip"),new File(Environment.getExternalStorageDirectory().getAbsolutePath()+File.separator+"test"))
     */
    public static void unzip(File source, File dest) throws IOException {
        ZipFile zipFile = new ZipFile(source);
        try {
            if(!dest.exists()){
                dest.mkdirs();
            }
            ZipInputStream zis = new ZipInputStream(new BufferedInputStream(new FileInputStream(source)));
            ZipEntry entry;
            byte[] buffer = new byte[1024];
            while((entry=zis.getNextEntry())!=null) {
                String filename = entry.getName();
                //排除MACOS环境下生成的隐藏文件
                if (filename.contains("__MACOSX")) {
                }
                else {
                    if (entry.isDirectory()) {
                        new File(dest,filename).mkdirs();
                        continue;
                    }
                    InputStream inputStream=zipFile.getInputStream(entry);
                    int len;
                    try (FileOutputStream outputStream =new FileOutputStream(new File(dest, filename))) {
                        while ((len = inputStream.read(buffer)) >= 0) {
                            outputStream.write(buffer, 0, len);
                        }
                        outputStream.flush();
                        inputStream.close();
                    }
                }
                zis.closeEntry();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            zipFile.close();
        }
    }

 

posted @ 2020-07-14 10:39  南极冰川雪  阅读(934)  评论(0编辑  收藏