java 提取(解壓)zip文件中特定后綴的文件並保存到指定目錄


內容簡介

本文主要介紹使用ZipFile來提取zip壓縮文件中特定后綴(如:png,jpg)的文件並保存到指定目錄下。

導入包:import java.util.zip.ZipFile;

如需添加對rar壓縮格式的支持,請參考我的另一篇文章:https://www.cnblogs.com/codecat/p/11078485.html

實現代碼(僅供參考,請根據實現情況來修改)

/**
 * 將壓縮文件中指定后綴名稱的文件解壓到指定目錄
 * @param compressFile 壓縮文件
 * @param baseDirectory 解壓到的基礎目錄(在此目錄下創建UUID的目錄,存入解壓的文件)
 * @param decompressSuffs 要提取文件的后綴名
 * @return
 */
@Override
public void decompressToUUIDDirectory(File compressFile, String baseDirectory, List<String> decompressSuffs) throws Exception {
    List<AttachFile> attachFileList = new ArrayList<>();

    //驗證壓縮文件
    boolean isFile = compressFile.isFile();
    if (!isFile){
        System.out.println(String.format("compressFile非文件格式!",compressFile.getName()));
        return null;
    }
    String compressFileSuff = FileUtil.getFileSuffix(compressFile.getName()).toLowerCase();
    if (!compressFileSuff.equals("zip")){
        System.out.println(String.format("[%s]文件非zip類型的壓縮文件!",compressFile.getName()));
        return null;
    }

    //region 解壓縮文件(zip)
    ZipFile zip = new ZipFile(new File(compressFile.getAbsolutePath()), Charset.forName("GBK"));//解決中文文件夾亂碼
    for (Enumeration<? extends ZipEntry> entries = zip.entries(); entries.hasMoreElements();){
        ZipEntry entry = entries.nextElement();
        String zipEntryName = entry.getName();
        //過濾非指定后綴文件
        String suff = FileUtil.getFileSuffix(zipEntryName).toLowerCase();
        if (decompressSuffs != null && decompressSuffs.size() > 0){
            if (decompressSuffs.stream().filter(s->s.equals(suff)).collect(Collectors.toList()).size() <= 0){
                continue;
            }
        }
        //創建解壓目錄(如果復制的代碼,這里會報錯,沒有StrUtil,這里就是創建了一個目錄來存儲提取的文件,你可以換其他方式來創建目錄)
        String groupId = StrUtil.getUUID();
        File group = new File(baseDirectory + groupId);
        if(!group.exists()){
            group.mkdirs();
        }
        //解壓文件到目錄
        String outPath = (baseDirectory + groupId + File.separator + zipEntryName).replaceAll("\\*", "/");
        InputStream in = zip.getInputStream(entry);
        FileOutputStream out = new FileOutputStream(outPath);
        byte[] buf1 = new byte[1024];
        int len;
        while ((len = in.read(buf1)) > 0) {
            out.write(buf1, 0, len);
        }
        in.close();
        out.close();
    }
    //endregion
}

 

ZipFile


免責聲明!

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



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