[java] ZIP 압축 방법을 사용하여 자바 애플리케이션 데이터 압축하기

애플리케이션에서 파일이나 데이터를 압축하고 해제하는 기능은 중요합니다. 이를 통해 디스크 공간을 절약하고 파일 전송 시간을 단축할 수 있습니다. Java에서는 java.util.zip 패키지를 사용하여 파일이나 데이터를 ZIP 포맷으로 압축하고 해제할 수 있습니다.

1. ZIP 파일 생성하기

ZIP 파일을 생성하기 위해 ZipOutputStream 클래스를 사용합니다. 아래는 간단한 예제 코드입니다.

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

public class ZipExample {
    public static void main(String[] args) {
        try {
            String sourceFile = "example.txt";
            FileOutputStream fos = new FileOutputStream("compressed.zip");
            ZipOutputStream zipOut = new ZipOutputStream(fos);
            File fileToZip = new File(sourceFile);
            FileInputStream fis = new FileInputStream(fileToZip);
            ZipEntry zipEntry = new ZipEntry(fileToZip.getName());
            zipOut.putNextEntry(zipEntry);
            byte[] bytes = new byte[1024];
            int length;
            while ((length = fis.read(bytes)) >= 0) {
                zipOut.write(bytes, 0, length);
            }
            zipOut.close();
            fis.close();
            fos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

2. ZIP 파일 해제하기

이제 위에서 생성한 ZIP 파일을 해제할 수 있습니다. ZipInputStream 클래스를 사용하여 이 작업을 수행할 수 있습니다. 아래는 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 UnzipExample {
    public static void main(String[] args) {
        byte[] buffer = new byte[1024];
        try {
            File folder = new File("unzip");
            if (!folder.exists()) {
                folder.mkdir();
            }
            ZipInputStream zis = new ZipInputStream(new FileInputStream("compressed.zip"));
            ZipEntry zipEntry = zis.getNextEntry();
            while (zipEntry != null) {
                File newFile = newFile(folder, zipEntry);
                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();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static File newFile(File destinationDir, ZipEntry zipEntry) throws IOException {
        File destFile = new File(destinationDir, zipEntry.getName());
        String destDirPath = destinationDir.getCanonicalPath();
        String destFilePath = destFile.getCanonicalPath();
        if (!destFilePath.startsWith(destDirPath + File.separator)) {
            throw new IOException("Entry is outside of the target dir: " + zipEntry.getName());
        }
        return destFile;
    }
}

위 코드에서는 ZipEntryZipInputStream을 사용하여 ZIP 파일을 해제하고 원하는 위치에 파일을 생성합니다.

ZIP 파일을 생성하고 해제하는 과정을 통해 Java에서 데이터를 압축하고 압축을 해제하는 방법에 대해 간단히 살펴보았습니다. 이러한 기능은 파일 처리 및 데이터 전송과 관련된 여러 시나리오에서 유용하게 활용될 수 있습니다.