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

먼저, Java에서 GZIP를 사용하여 디렉토리를 압축하는 방법을 알아보겠습니다.

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

public class GzipDirectory {
    public static void main(String[] args) {
        String sourceDirPath = "/path/to/source/directory";
        String targetGzipFilePath = "/path/to/target/archive.tar.gz";

        try {
            FileOutputStream fos = new FileOutputStream(targetGzipFilePath);
            GZIPOutputStream gzipOS = new GZIPOutputStream(fos);
            TarOutputStream tarOS = new TarOutputStream(gzipOS);

            addFilesToTarGz(sourceDirPath, tarOS, "");

            tarOS.close();
            gzipOS.close();
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void addFilesToTarGz(String folderToArchive, TarOutputStream tos, String relativePath) throws IOException {
        File f = new File(folderToArchive);
        String entryName = relativePath + f.getName() + "/";

        TarEntry tarEntry = new TarEntry(f, entryName);
        tos.putNextEntry(tarEntry);
        tos.closeEntry();

        if (f.isFile()) {
            FileInputStream fis = new FileInputStream(f);
            BufferedInputStream bis = new BufferedInputStream(fis);

            byte[] data = new byte[1024];
            int byteCount;
            while ((byteCount = bis.read(data)) != -1) {
                tos.write(data, 0, byteCount);
            }

            bis.close();
            fis.close();
        } else if (f.isDirectory()) {
            for (File child : f.listFiles()) {
                addFilesToTarGz(child.getAbsolutePath(), tos, entryName);
            }
        }
    }
}

위의 예제는 Java에서 GZIP를 사용하여 디렉토리를 압축하는 방법을 보여줍니다. 이 코드는 지정된 소스 디렉토리의 파일을 타르로 압축하고, GZIP를 사용하여 결과를 압축합니다.

이제, 위의 예제를 사용하여 디렉토리를 GZIP로 압축할 수 있습니다. 위의 코드를 참고하여 직접 수정하여 사용하거나 자신의 요구 사항에 맞게 구성할 수 있습니다.

기타 참고 자료: