[java] ZIP 압축 방법을 사용하여 디렉토리 압축하기

우선, ZipOutputStream을 사용하여 디렉토리를 압축할 수 있습니다. 아래는 간단한 예제 코드입니다.

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

public class ZipDirectory {
    public static void main(String[] args) throws IOException {
        String sourceDir = "path_to_source_directory";
        String zipFile = "path_to_zip_file.zip";

        FileOutputStream fos = new FileOutputStream(zipFile);
        ZipOutputStream zos = new ZipOutputStream(fos);

        addDirToArchive(zos, new File(sourceDir), "");

        zos.flush();
        fos.close();
        zos.close();
    }

    private static void addDirToArchive(ZipOutputStream zos, File sourceDir, String parentDir) throws IOException {
        File[] files = sourceDir.listFiles();
        byte[] buffer = new byte[1024];

        for (File file : files) {
            if (file.isDirectory()) {
                addDirToArchive(zos, file, parentDir + file.getName() + "/");
                continue;
            }

            FileInputStream fis = new FileInputStream(file);
            zos.putNextEntry(new ZipEntry(parentDir + file.getName()));

            int length;
            while ((length = fis.read(buffer)) > 0) {
                zos.write(buffer, 0, length);
            }

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

이 코드는 지정된 디렉토리의 모든 파일과 하위 디렉토리를 ZIP 파일로 압축합니다. ZipOutputStream을 사용하여 ZIP 파일을 생성하고, addDirToArchive 메서드를 통해 디렉토리를 압축합니다.

이제 위의 코드를 사용하여 디렉토리를 ZIP 파일로 압축할 수 있습니다.