apache. comons. copress 압축 및 가압 파일 도구 류 사용 하기

13020 단어 Java
package com.my.common.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.archivers.ArchiveEntry;
import org.apache.commons.compress.archivers.zip.Zip64Mode;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveInputStream;
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;

import java.io.*;

/**
 *      
 *
 * @author helloworld
 */
@Slf4j
public class ZipUtil {

    /**
     *       zip     
     *
     * @param files                    
     * @param zipFile                
     * @param deleteFileAfterZip             ,         
     * @return       
     */
    public static boolean compressFiles2Zip(List files, File zipFile, boolean deleteFileAfterZip) {

        InputStream inputStream = null;
        ZipArchiveOutputStream zipArchiveOutputStream = null;
        try {
            zipArchiveOutputStream = new ZipArchiveOutputStream(zipFile);
            //Use Zip64 extensions for all entries where they are required
            zipArchiveOutputStream.setUseZip64(Zip64Mode.AsNeeded);
            for (File file : files) {
                //      ZipArchiveEntry  ,  ZipArchiveOutputStream      
                ZipArchiveEntry zipArchiveEntry = new ZipArchiveEntry(file, file.getName());
                zipArchiveOutputStream.putArchiveEntry(zipArchiveEntry);

                inputStream = new FileInputStream(file);
                byte[] buffer = new byte[1024 * 5];
                int len = -1;
                while ((len = inputStream.read(buffer)) != -1) {
                    //          ZipArchiveEntry
                    zipArchiveOutputStream.write(buffer, 0, len);
                }
            }
            zipArchiveOutputStream.closeArchiveEntry();
            zipArchiveOutputStream.finish();

            if (deleteFileAfterZip) {
                for (File file : files) {
                    file.deleteOnExit();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        } finally {
            try {
                //     
                if (null != inputStream) {
                    inputStream.close();
                }
                //     
                if (null != zipArchiveOutputStream) {
                    zipArchiveOutputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return true;
    }

    /**
     *  zip              
     *
     * @param zipFilePath         
     * @param targetDirPath        
     * @return     
     */
    public static boolean decompressZip2Files(String zipFilePath, String targetDirPath) {

        InputStream inputStream = null;
        OutputStream outputStream = null;
        //zip     
        ZipArchiveInputStream zipArchiveInputStream = null;
        ArchiveEntry archiveEntry = null;
        try {
            File zipFile = new File(zipFilePath);
            inputStream = new FileInputStream(zipFile);
            zipArchiveInputStream = new ZipArchiveInputStream(inputStream, "UTF-8");

            while (null != (archiveEntry = zipArchiveInputStream.getNextEntry())) {
                //     
                String archiveEntryFileName = archiveEntry.getName();
                //            
                String archiveEntryPath = targetDirPath + archiveEntryFileName;
                //              
                File entryFile = new File(archiveEntryPath);
                if (!entryFile.exists()) {
                    boolean mkdirs = entryFile.getParentFile().mkdirs();

                }
                byte[] buffer = new byte[1024 * 5];
                outputStream = new FileOutputStream(entryFile);
                int len = -1;
                while ((len = zipArchiveInputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, len);
                }
                outputStream.flush();
            }
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        } finally {
            try {
                if (null != outputStream) {
                    outputStream.close();
                }
                if (null != zipArchiveInputStream) {
                    zipArchiveInputStream.close();
                }
                if (null != inputStream) {
                    inputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return true;
    }

    /**
     *       zip     
     *
     * @param docs             
     * @param targetFile     
     * @return       
     */
    public static boolean compressDoc2Zip(List> docs, File targetFile) throws IOException {
        List fileList = new ArrayList<>();
        for (Pair doc : docs) {
            String name = doc.getFirst();
            XWPFDocument document = doc.getSecond();
            File file = convertDocument2File(document, name);
            fileList.add(file);
        }
        return compressFiles2Zip(fileList, targetFile, true);
    }

    /**
     *  XWPFDocument  File
     *
     * @param document    
     * @param fileName file  
     * @return     file
     * @throws IOException      
     */
    public static File convertDocument2File(XWPFDocument document, String fileName) throws IOException {
        if (fileName.length() <= 3) {
            fileName += "-" + DateFormatUtils.format(new Date(), "yyyyMMddHHmmss");
        }
        if (!fileName.endsWith("docx")) {
            fileName += ".docx";
        }

        File file = createTempFile(fileName);
        try (OutputStream os = new FileOutputStream(file)) {
            document.write(os);
        }

        return file;
    }

    /**
     *        
     */
    public static File createTempFile(String fullFileName) throws IOException {
        String tempDirectoryPath = FileUtils.getTempDirectoryPath();
        File file = new File(tempDirectoryPath + File.separator + fullFileName);
        file.deleteOnExit();
        boolean newFile = file.createNewFile();
        log.debug("newFile {} => {}", fullFileName, newFile);
        return file;
    }

    public static void main(String[] args) {
        File f1 = new File("/Users/my/Desktop/WechatIMG78.jpeg");
        File f2 = new File("/Users/my/Desktop/WechatIMG79.jpeg");
        File f3 = new File("/Users/my/Desktop/aaaaa.docx");

        //      
        boolean b = compressFiles2Zip(new File[]{f1, f2, f3}, "/Users/my/Desktop/haha.zip");
        log.info("compressFiles2Zip={}", b);

        //      
        boolean b1 = decompressZip2Files("/Users/my/Desktop/haha.zip", "/Users/zhangbaozhen/my/hahaha/");
        log.info("decompressZip2Files={}", b1);
    }

}

좋은 웹페이지 즐겨찾기