解壓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();
        }
    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM