[java] 자바에서 압축된 데이터를 압축 해제하는 방법

Java에서는 다양한 방법으로 압축된 데이터를 압축 해제할 수 있습니다. 이 글에서는 java.util.zip 패키지를 이용한 압축 해제 방법을 알아보겠습니다.

1. java.util.zip 패키지

java.util.zip 패키지는 자바에서 압축 파일을 다루기 위한 클래스와 인터페이스를 제공합니다. 이 패키지를 사용하여 압축된 데이터를 해제할 수 있습니다.

2. 압축 해제 예제

다음은 java.util.zip 패키지를 사용하여 압축된 데이터를 해제하는 예제 코드입니다.

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

public class ZipExtractor {
    public static void main(String[] args) {
        String zipFilePath = "path/to/your/file.zip";
        String destDirectory = "path/to/extract/folder";
        
        try {
            unzip(zipFilePath, destDirectory);
            System.out.println("압축 해제가 완료되었습니다.");
        } catch (IOException e) {
            System.out.println("압축 해제 중 오류가 발생하였습니다: " + e.getMessage());
        }
    }
    
    public static void unzip(String zipFilePath, String destDirectory) throws IOException {
        File destDir = new File(destDirectory);
        if (!destDir.exists()) {
            destDir.mkdir();
        }
        
        byte[] buffer = new byte[1024];
        ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(zipFilePath));
        ZipEntry zipEntry = zipInputStream.getNextEntry();
        while (zipEntry != null) {
            String fileName = zipEntry.getName();
            File newFile = new File(destDirectory + File.separator + fileName);
            
            // 디렉토리인 경우 생성
            if (zipEntry.isDirectory()) {
                newFile.mkdirs();
            } else {
                // 파일인 경우 압축 해제
                FileOutputStream fos = new FileOutputStream(newFile);
                int len;
                while ((len = zipInputStream.read(buffer)) > 0) {
                    fos.write(buffer, 0, len);
                }
                fos.close();
            }
            zipEntry = zipInputStream.getNextEntry();
        }
        zipInputStream.closeEntry();
        zipInputStream.close();
    }
}

위의 예제 코드는 unzip 메서드를 사용하여 압축 해제를 수행합니다.

압축된 파일의 경로(zipFilePath)와 압축 해제 후 파일이 저장될 폴더의 경로(destDirectory)를 매개변수로 받습니다.

해당 폴더가 없는 경우에는 새로 생성합니다. 압축 파일을 열고 각 엔트리를 읽어와 디렉토리인 경우 폴더를 생성하고 파일인 경우 압축 해제 작업을 수행합니다.

3. 실행

위의 예제 코드를 실행하기 위해서는 압축 파일의 경로(zipFilePath)와 압축 해제 후 파일이 저장될 폴더의 경로(destDirectory)를 적절히 설정해주어야 합니다.

압축 해제가 완료되면 “압축 해제가 완료되었습니다.” 라는 메시지가 출력됩니다. 만약 압축 해제 중 오류가 발생하면 오류 메시지가 출력됩니다.

4. 결론

Java에서 압축된 데이터를 압축 해제하는 방법에 대해 알아보았습니다. java.util.zip 패키지를 사용하여 간단하게 압축 해제 작업을 수행할 수 있습니다. 이를 응용하여 다양한 압축 포맷을 처리하거나 추가적인 작업을 수행할 수 있습니다.