본문 바로가기
Java

[Java] zip4j 라이브러리 사용하여 압축

by Alohawaii 2022. 2. 27.

프로젝트 중 파일관련 압축할 일이 생겨 해당 내용을 정리한다.
zip4j 라이브러리를 사용하여 코드를 구현하였다.

 zip4j를 사용하기위해 maven에 추가하고,  byte array로 받은 내용을 파일에 쓰기 위해 commons-io의 FileUtils도 사용하였다. 

        <dependency>
            <groupId>net.lingala.zip4j</groupId>
            <artifactId>zip4j</artifactId>
            <version>1.3.2</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.11.0</version>
        </dependency>

 

zip4j에서 제공하는 메서드는 여러파일 압축과 폴더하위파일 압축, 그리고 파일명과 byte 배열로 전달된 내용을 압축하는 메서드를 구현하였다.

public static void main(String[] args) throws Exception {
        FileZipSample fileZipSample = new FileZipSample();

        File file1 = new File("c:\\workspace\\sample1.txt");
        File file2 = new File("c:\\workspace\\sample2.txt");

        ArrayList<File> files = new ArrayList<>();
        files.add(file1);
        files.add(file2);

//        fileZipSample.filesZip(files);
//        fileZipSample.folderZip("c:\\workspace");

        File file3 = new File("c:\\workspace\\sample1.txt");
        File file4 = new File("c:\\workspace\\sample2.txt");

        byte[] bytes1 = FileUtils.readFileToByteArray(file3);
        byte[] bytes2 = FileUtils.readFileToByteArray(file4);

        ZipFileVO zipFileVO1 = new ZipFileVO();
        ZipFileVO zipFileVO2 = new ZipFileVO();

        zipFileVO1.setFileName("c:\\workspace\\sample3.txt");
        zipFileVO2.setFileName("c:\\workspace\\sample4.txt");

        zipFileVO1.setFileData(bytes1);
        zipFileVO2.setFileData(bytes2);

        ArrayList<ZipFileVO> zipFileVOS = new ArrayList<>();
        zipFileVOS.add(zipFileVO1);
        zipFileVOS.add(zipFileVO2);

        fileZipSample.byteArrayZip(zipFileVOS);



    }

    private ZipParameters parameters = null;

    private ZipParameters getZipParameters() {
        // 압축 설정
        if (null == parameters) {
            parameters = new ZipParameters();
            // 압축을 위해 사용될 알고리즘을 가리킴
            parameters.setCompressionMethod(Zip4jConstants.COMP_STORE);
            // 압축레벨
            parameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_FASTEST);
        }
        return parameters;
    }

    // 여러파일 압축
    public File filesZip(ArrayList<File> filePathNameList) throws  Exception {
        try{
            if (filePathNameList == null || filePathNameList.isEmpty()) {
                throw new Exception("error");
            }

            String zipFileName = UUID.randomUUID() + ".zip";
            ZipFile zipFile = new ZipFile("c:\\workspace\\" + zipFileName);

            ZipParameters parameters = getZipParameters();
            zipFile.addFiles(filePathNameList, parameters);

            return zipFile.getFile();
        } catch (Exception e) {
            throw new Exception();
        }
    }

    // 폴더하위파일 압축
    public File folderZip(String folderPath) throws Exception {
        try {
            if (StringUtils.isEmpty(folderPath)) {
                throw new Exception();
            }

            String zipFileName = UUID.randomUUID() + ".zip";
            ZipParameters zipParameters = getZipParameters();

            ZipFile zipFile = new ZipFile("c:\\workspace\\" + zipFileName);
            zipFile.addFolder(folderPath, zipParameters);

            return zipFile.getFile();
        } catch(Exception e) {
            e.printStackTrace();
            throw new Exception();
        }
    }

    // Byte Array 압축
    public File byteArrayZip(List<ZipFileVO> fileList) throws Exception {
        try {
            if (fileList == null || fileList.isEmpty()) {
                throw new Exception();
            }

            ArrayList<File> fileArrayList = new ArrayList<>();
            String zipFileName = UUID.randomUUID() + ".zip";

            for(ZipFileVO zipFileVO : fileList) {
                if(zipFileVO.getFileData() == null || zipFileVO.getFileData().length == 0) {
                    throw new Exception();
                }

                if (StringUtils.isEmpty(zipFileVO.getFileName())) {
                    throw new Exception();
                }

                // 파일 생성(domain에서 파일명 get) -> 해당 파일에 fileData write
                File file = new File(zipFileVO.getFileName());

                FileUtils.writeByteArrayToFile(file, zipFileVO.getFileData());
                // 해당 파일 배열에 추가
                fileArrayList.add(file);
            }

            // 여러파일 압축과 동일
            ZipFile zipFile = new ZipFile("c:\\workspace\\" + zipFileName);

            ZipParameters parameters = getZipParameters();
            zipFile.addFiles(fileArrayList, parameters);

            return zipFile.getFile();
        } catch(Exception e) {
            e.printStackTrace();
            throw new Exception();
        }
    }

 

[참고]

https://javadoc.io/doc/net.lingala.zip4j/zip4j/1.3.2/net/lingala/zip4j/model/

'Java' 카테고리의 다른 글

[Java] 람다식  (0) 2022.02.27
[Java] HTTP API 통신  (0) 2022.02.24