[java] ZIP 압축 방법을 사용하여 자바 파일 입출력 데이터 압축하기

파일 시스템에서 파일을 압축하고 압축 해제하는 것은 많은 자바 애플리케이션에서 필요한 작업입니다. 이를 위해 java.util.zip 패키지의 ZipOutputStreamZipInputStream 클래스를 사용할 수 있습니다. 이 블로그에서는 자바에서 ZIP 압축 방법을 사용하여 파일을 압축하고, 압축된 데이터를 파일 시스템에 저장하거나 전송하는 방법을 알아보겠습니다.

1. 파일을 ZIP으로 압축하기

ZipOutputStream 클래스를 사용하여 파일을 ZIP으로 압축하는 방법은 다음과 같습니다.

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

public class ZipUtility {
    public static void zipFile(String sourceFilePath, String zipFilePath) {
        try (FileOutputStream fos = new FileOutputStream(zipFilePath);
             ZipOutputStream zos = new ZipOutputStream(fos)) {
            File fileToZip = new File(sourceFilePath);
            try (FileInputStream fis = new FileInputStream(fileToZip)) {
                ZipEntry zipEntry = new ZipEntry(fileToZip.getName());
                zos.putNextEntry(zipEntry);
                byte[] bytes = new byte[1024];
                int length;
                while ((length = fis.read(bytes)) >= 0) {
                    zos.write(bytes, 0, length);
                }
                zos.closeEntry();
            }
        }
    }
}

위의 코드 예제에서는 ZipUtility 클래스에 zipFile 메서드를 사용하여 파일을 압축합니다.

2. ZIP 파일 압축 해제하기

이어서, ZipInputStream 클래스를 사용하여 ZIP 파일을 압축 해제하는 방법을 살펴보겠습니다.

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

public class UnzipUtility {
    public static void unzipFile(String zipFilePath, String destDirectory) throws IOException {
        File destDir = new File(destDirectory);
        if (!destDir.exists()) {
            destDir.mkdir();
        }
        try (ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFilePath))) {
            ZipEntry zipEntry = zis.getNextEntry();
            while (zipEntry != null) {
                File newFile = newFile(destDir, zipEntry);
                try (FileOutputStream fos = new FileOutputStream(newFile)) {
                    byte[] buffer = new byte[1024];
                    int len;
                    while ((len = zis.read(buffer)) > 0) {
                        fos.write(buffer, 0, len);
                    }
                }
                zipEntry = zis.getNextEntry();
            }
            zis.closeEntry();
        }
    }

    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;
    }
}

위의 코드 예제에서는 UnzipUtility 클래스에 unzipFile 메서드를 사용하여 ZIP 파일을 압축 해제합니다.

이제 두 가지 방법을 사용하여 파일을 압축하고 압축을 해제하는 방법을 살펴 보았습니다. 파일 시스템에서 데이터를 효율적으로 압축하고 압축을 해제하는 것은 자바 애플리케이션에서 유용하며, 위의 예시를 통해 간단한 방법으로 구현할 수 있음을 알 수 있습니다.

참고 자료