여윽시 압축/압축해제를 구현할 일이 생겼다. 대충 그래서 몇가지 라이브러리를 테스트 해 보니 zip4j가 가장 무난하고 속도도 빨랐다. 사용법도 간편하고.

개인적으로 java.util 에서 구현하는 zip 유틸은 쓰기가 좀 귀찮은데(설정할게 많음) 거기에 fileinputstream으로 구현하니 엄청 느리더라. 100메가 csv 압축하는데 20분 걸리던가. buffer로 구현하면 조금 더 빨라진다는데, 사실 이런걸 직접 구현하는 재미도 있긴 하지만 나보다는 더 똑똑한 사람들이 구현해놓은 라이브러리를 갖다 쓰는게 더 낫지 않을까. 아무튼, 해봤다.

 

1. pom.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<!-- Spring Boot 2.7.8 에서 설정함 -->
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.7.8</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>
 
<!-- https://mvnrepository.com/artifact/net.lingala.zip4j/zip4j -->
<dependency>
    <groupId>net.lingala.zip4j</groupId>
    <artifactId>zip4j</artifactId>
    <version>2.11.5</version>
</dependency>
cs

 

대충 스프링부트 2.7.8 , zip4j 는 2.11.5를 썼다 이마리야

 

 

2. 파일 압축

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
import net.lingala.zip4j.ZipFile;
import net.lingala.zip4j.exception.ZipException;
import net.lingala.zip4j.model.ZipParameters;
import net.lingala.zip4j.util.Zip4jConstants;
 
import java.io.File;
 
public class SingleFileCompressionExample {
    public static void main(String[] args) {
        // 압축대상 파일 경로
        String sourceFilePath = "path/to/source/file.txt";
        // 압축결과 파일 경로
        String zipFilePath = "path/to/output.zip";
        // 암호를 사용할 경우
        String password = "yourPassword";
        
        try {
            ZipFile zipFile = new ZipFile(zipFilePath);
            zipFile.addFile(new File(sourceFilePath), createZipParameters(password));
            
            System.out.println("File compressed successfully!");
        } catch (ZipException e) {
            System.err.println("Error compressing file: " + e.getMessage());
        }
    }
    
    private static ZipParameters createZipParameters(String password) {
        ZipParameters zipParameters = new ZipParameters();
        
        zipParameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE);
        zipParameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_ULTRA;
        
        // 패스워드를 정하는 경우, 여기에서 zipParameter에 암호 알고리즘 적용함
        if (password != null && !password.isEmpty()) {
            // 암호사용여부
            zipParameters.setEncryptFiles(true);  
            // 암호 알고리즘
            zipParameters.setEncryptionMethod(Zip4jConstants.ENC_METHOD_STANDARD);
            // 적용할 암호
            zipParameters.setPassword(password);
        }
        
        return zipParameters;
    }
}
cs

 

 

3. 파일 압축 해제

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import net.lingala.zip4j.ZipFile;
import net.lingala.zip4j.exception.ZipException;
 
public class FileDecompressionExample {
    public static void main(String[] args) {
 
        // 압축해제 대상파일
        String zipFilePath = "path/to/input.zip";
        
        // 압축해제 대상 디렉토리
        String destDirectory = "path/to/destination";
        
        // 암호가 있는 경우
        String password = "yourPassword"// Set to null if the ZIP file is not encrypted
        
        try {
            ZipFile zipFile = new ZipFile(zipFilePath);
            
            // 암호가 있는 경우를 체크해서 적용함
            if (zipFile.isEncrypted() && password != null) {
                zipFile.setPassword(password);
            }
            
            zipFile.extractAll(destDirectory);
            
            System.out.println("Files extracted successfully!");
        } catch (ZipException e) {
            System.err.println("Error extracting files: " + e.getMessage());
        }
    }
}
 
cs

 

 

chatGPT 에게 물어보고 적용한건데 생각보다 너무 쉽게 잘 짜주어서 놀랐다. 앞으로 종종 써먹어야지.

블로그 이미지

김생선

세상의 모든것을 어장관리

,