SeouliteLab

[Java/자바] ZIP 압축, 압축 해제 (zip, unzip) 본문

프로그래밍

[Java/자바] ZIP 압축, 압축 해제 (zip, unzip)

Seoulite Lab 2024. 3. 9. 01:11

ZIP은 여러 파일이나 디렉토리를 하나의 파일로 압축하는 방법 중 가장 널리 사용되는 방법 중 하나입니다. Java에서는 ZIP 파일의 생성과 압축 해제를 쉽게 처리할 수 있는 클래스와 메서드를 제공합니다. 이번 글에서는 Java에서 ZIP 파일을 압축하고 압축을 해제하는 방법에 대해 알아보겠습니다.

1. ZIP 파일 생성하기

Java에서는 ZipOutputStream 클래스를 사용하여 ZIP 파일을 생성할 수 있습니다. ZipOutputStream을 사용하면 파일이나 디렉토리를 압축하여 ZIP 파일을 생성할 수 있습니다.

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

public class ZipExample {
    public static void main(String[] args) throws IOException {
        String sourceFile = "source.txt";
        String zipFile = "compressed.zip";
        
        // ZIP 파일 생성
        try (FileOutputStream fos = new FileOutputStream(zipFile);
             ZipOutputStream zos = new ZipOutputStream(fos)) {
            // 파일 추가
            addToZipFile(sourceFile, zos);
        }
    }

    private static void addToZipFile(String fileName, ZipOutputStream zos) throws IOException {
        File file = new File(fileName);
        FileInputStream fis = new FileInputStream(file);
        ZipEntry zipEntry = new ZipEntry(file.getName());
        zos.putNextEntry(zipEntry);

        byte[] bytes = new byte[1024];
        int length;
        while ((length = fis.read(bytes)) >= 0) {
            zos.write(bytes, 0, length);
        }
        zos.closeEntry();
        fis.close();
    }
}

2. ZIP 파일 압축 해제하기

ZIP 파일을 압축 해제하는 것은 ZipInputStream 클래스를 사용하여 수행할 수 있습니다. ZipInputStream을 사용하면 ZIP 파일에서 개별 파일을 읽어들일 수 있습니다.

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

public class UnzipExample {
    public static void main(String[] args) throws IOException {
        String zipFilePath = "compressed.zip";
        String destDirectory = "unzipped";

        // ZIP 파일 압축 해제
        try (ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFilePath))) {
            ZipEntry zipEntry = zis.getNextEntry();
            while (zipEntry != null) {
                String fileName = zipEntry.getName();
                File newFile = new File(destDirectory + File.separator + fileName);
                new File(newFile.getParent()).mkdirs();
                FileOutputStream fos = new FileOutputStream(newFile);
                byte[] bytes = new byte[1024];
                int length;
                while ((length = zis.read(bytes)) >= 0) {
                    fos.write(bytes, 0, length);
                }
                fos.close();
                zipEntry = zis.getNextEntry();
            }
            zis.closeEntry();
        }
    }
}