[java] 자바에서 ZIP 파일 해제하기

이번 포스트에서는 자바에서 ZIP 파일을 해제하는 방법에 대해 알아보겠습니다. ZIP 파일을 해제하는 기능은 파일 및 폴더를 압축하여 전송하거나 저장한 후, 필요할 때 이를 해제하여 원래의 파일 및 폴더 구조를 되찾을 수 있도록 해줍니다.

java.util.zip 패키지를 사용한 ZIP 파일 해제

java.util.zip 패키지에는 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 UnzipFile {
    public static void unzip(String zipFilePath, String destDir) throws IOException {
        File destDirectory = new File(destDir);
        if (!destDirectory.exists()) {
            destDirectory.mkdir();
        }
        
        byte[] buffer = new byte[1024];
        ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFilePath));
        ZipEntry zipEntry = zis.getNextEntry();
        
        while (zipEntry != null) {
            String fileName = zipEntry.getName();
            File newFile = new File(destDir + File.separator + fileName);
            
            if (zipEntry.isDirectory()) {
                newFile.mkdirs();
            } else {
                FileOutputStream fos = new FileOutputStream(newFile);
                int length;
                while ((length = zis.read(buffer)) > 0) {
                    fos.write(buffer, 0, length);
                }
                fos.close();
            }
            
            zis.closeEntry();
            zipEntry = zis.getNextEntry();
        }
        zis.closeEntry();
        zis.close();
    }
    
    public static void main(String[] args) {
        String zipFilePath = "path/to/your/file.zip";
        String destDir = "path/to/destination/folder";
        try {
            unzip(zipFilePath, destDir);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

위의 예제 코드는 UnzipFile 클래스를 정의하고, unzip 메서드를 사용하여 ZIP 파일을 해제하는 기능을 구현한 것입니다. main 메서드에서는 사용 예시를 보여줍니다.

마치며

이제 자바에서 ZIP 파일을 해제하는 방법에 대해 알아보았습니다. 자바의 java.util.zip 패키지를 활용하면 간단하게 ZIP 파일을 해제할 수 있습니다. ZIP 파일 처리를 자주 다루어야 하는 경우, 관련된 자바 문서 및 레퍼런스들을 참고하여 보다 다양한 기능을 활용해보시기 바랍니다.

자바 공식 문서 및 레퍼런스: Java SE Documentation

저작권 © 2021, [Your Name].getPostByAssistant