[java] ZIP 압축 방법을 사용하여 자바 데이터 압축 오류 처리하기

ZIP는 자바에서 파일 압축 및 해제에 널리 사용되는 형식입니다. ZIP 파일을 생성하고 압축을 해제하는 방법을 살펴보겠습니다.

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.ZipOutputStream;

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

위의 코드는 FileZipper 클래스에 zipFile 메서드를 정의하여 주어진 파일을 ZIP 파일로 압축하고 지정된 경로에 저장하는 기능을 구현합니다.

ZIP 파일 압축 해제

이제 압축된 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 FileUnzipper {
    public static void unzipFile(String zipFilePath, String destDirectory) throws IOException {
        File destDir = new File(destDirectory);
        if (!destDir.exists()) {
            destDir.mkdirs();
        }
        try (ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFilePath))) {
            ZipEntry entry;
            while ((entry = zis.getNextEntry()) != null) {
                File entryFile = new File(destDirectory, entry.getName());
                if (entry.isDirectory()) {
                    entryFile.mkdirs();
                } else {
                    try (FileOutputStream fos = new FileOutputStream(entryFile)) {
                        byte[] buffer = new byte[1024];
                        int length;
                        while ((length = zis.read(buffer)) > 0) {
                            fos.write(buffer, 0, length);
                        }
                    }
                }
            }
        }
    }
}

위의 코드는 FileUnzipper 클래스에 unzipFile 메서드를 정의하여 주어진 ZIP 파일을 지정된 디렉토리에 압축 해제하는 기능을 구현합니다.

위의 코드들을 사용하여 ZIP 파일 생성 및 압축 해제를 자유롭게 수행할 수 있습니다.

이제 자바에서 ZIP 파일을 생성하고 압축을 해제하는 방법에 대한 예제를 살펴보았습니다.

자세한 내용은 Oracle Java Documentation을 참조하시기 바랍니다.