[java] ZIP 압축 방법 이해하기

ZIP 파일 형식은 여러 파일을 하나의 압축된 파일로 묶어주는데 사용됩니다. 이번 글에서는 Java에서 ZIP 파일을 압축하고 해제하는 방법에 대해 알아보겠습니다.

1. ZIP 파일 압축하기

ZIP 파일을 압축하기 위해서는 java.util.zip 패키지의 ZipOutputStream 클래스를 활용할 수 있습니다. 아래는 간단한 예제 코드입니다.

import java.io.*;
import java.util.zip.*;

public class ZipExample {

    public static void main(String[] args) throws IOException {
        String sourceFile = "example.txt";
        String zipFile = "example.zip";

        FileOutputStream fos = new FileOutputStream(zipFile);
        ZipOutputStream zos = new ZipOutputStream(fos);
        ZipEntry ze = new ZipEntry(sourceFile);

        zos.putNextEntry(ze);
        FileInputStream in = new FileInputStream(sourceFile);

        int len;
        byte[] buffer = new byte[1024];
        while ((len = in.read(buffer)) > 0) {
            zos.write(buffer, 0, len);
        }

        in.close();
        zos.closeEntry();
        zos.close();
    }
}

2. ZIP 파일 해제하기

이어서 압축된 ZIP 파일을 해제하는 방법에 대해 살펴보겠습니다. Java에서는 ZipInputStream 클래스를 사용하여 ZIP 파일을 해제할 수 있습니다. 아래는 ZIP 파일을 해제하는 간단한 예제 코드입니다.

import java.io.*;
import java.util.zip.*;

public class UnzipExample {

    public static void main(String[] args) throws IOException {
        String zipFile = "example.zip";
        String destDir = "output";

        byte[] buffer = new byte[1024];

        ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFile));
        ZipEntry zipEntry = zis.getNextEntry();

        while (zipEntry != null) {
            String fileName = zipEntry.getName();
            File newFile = new File(destDir + File.separator + fileName);

            new File(newFile.getParent()).mkdirs();

            FileOutputStream fos = new FileOutputStream(newFile);
            int len;
            while ((len = zis.read(buffer)) > 0) {
                fos.write(buffer, 0, len);
            }
            fos.close();
            zipEntry = zis.getNextEntry();
        }
        zis.closeEntry();
        zis.close();
    }
}

이제 위 코드를 참고하여 Java에서 ZIP 파일을 압축하고 해제하는 방법에 대해 자세히 알아보았습니다.

참고 자료: Java ZipOutputStream, Java ZipInputStream