[java] 자바에서 압축된 데이터를 효율적으로 처리하는 방법

자바에서 압축된 데이터를 효율적으로 처리하는 방법을 알아보겠습니다.

1. 압축된 데이터 해제하기

Java에서는 java.util.zip 패키지를 통해 압축된 데이터를 해제할 수 있습니다. ZipInputStream 클래스를 사용하여 압축 파일의 내용을 읽고, ZipEntry 객체로부터 개별 엔트리를 획득할 수 있습니다.

다음은 압축된 파일을 읽고 해제하는 예제 코드입니다:

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

public class ZipFileExtractor {
    public static void extract(String zipFilePath, String targetDirectory) throws IOException {
        FileInputStream fis = new FileInputStream(zipFilePath);
        ZipInputStream zis = new ZipInputStream(fis);
        ZipEntry zipEntry = zis.getNextEntry();

        while (zipEntry != null) {
            String entryName = zipEntry.getName();
            String entryPath = targetDirectory + "/" + entryName;

            if (!zipEntry.isDirectory()) {
                FileOutputStream fos = new FileOutputStream(entryPath);
                byte[] buffer = new byte[1024];
                int read = 0;
                while ((read = zis.read(buffer)) != -1) {
                    fos.write(buffer, 0, read);
                }
                fos.close();
            } else {
                // 디렉토리인 경우 디렉토리 생성
                new File(entryPath).mkdirs();
            }

            zis.closeEntry();
            zipEntry = zis.getNextEntry();
        }

        zis.close();
        fis.close();
    }
}

위의 예제 코드는 주어진 zipFilePath에서 압축 파일을 읽고, targetDirectory에 파일을 추출합니다. ZipInputStream을 사용하여 압축 파일의 엔트리를 읽고, 파일인 경우에는 파일로 추출하고, 디렉토리인 경우 디렉토리를 생성합니다.

2. 압축된 데이터 생성하기

Java에서는 java.util.zip 패키지를 사용하여 압축된 데이터를 생성할 수도 있습니다. ZipOutputStream 클래스를 사용하여 압축 파일을 생성할 수 있습니다.

다음은 파일과 디렉토리를 압축 파일로 생성하는 예제 코드입니다:

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 ZipFileCreator {
    public static void create(String zipFilePath, String sourceDirectory) throws IOException {
        FileOutputStream fos = new FileOutputStream(zipFilePath);
        ZipOutputStream zos = new ZipOutputStream(fos);
        File sourceDir = new File(sourceDirectory);
        compressDirectory(sourceDir, sourceDir.getName(), zos);
        zos.close();
        fos.close();
    }

    private static void compressDirectory(File directory, String parentPath, ZipOutputStream zos) throws IOException {
        File[] files = directory.listFiles();

        for (File file : files) {
            if (file.isDirectory()) {
                compressDirectory(file, parentPath + "/" + file.getName(), zos);
            } else {
                zipFile(file, parentPath, zos);
            }
        }
    }

    private static void zipFile(File file, String parentPath, ZipOutputStream zos) throws IOException {
        byte[] buffer = new byte[1024];
        FileInputStream fis = new FileInputStream(file);
        String entryPath = parentPath + "/" + file.getName();
        ZipEntry zipEntry = new ZipEntry(entryPath);
        zos.putNextEntry(zipEntry);

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

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

위의 예제 코드는 주어진 sourceDirectory에 있는 파일과 디렉토리를 zipFilePath로 지정된 압축 파일로 생성합니다. ZipOutputStream을 사용하여 압축 파일을 생성하고, 디렉토리의 경우 재귀적으로 파일 및 하위 디렉토리를 압축 파일에 추가합니다.

3. 압축 알고리즘 설정하기

Java에서는 기본적으로 ZIP 압축 알고리즘을 사용합니다. 하지만 java.util.zip 패키지를 사용하여 다른 압축 알고리즘을 사용할 수도 있습니다. ZipOutputStream 또는 ZipInputStream 생성 시 두 번째 매개변수에 다른 알고리즘을 지정하면 됩니다.

다음은 Deflater 클래스를 사용하여 압축 알고리즘을 설정하는 예제 코드입니다:

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.Deflater;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class CompressedFileCreator {
    public static void create(String filePath) throws IOException {
        FileOutputStream fos = new FileOutputStream(filePath);
        ZipOutputStream zos = new ZipOutputStream(fos);
        zos.setLevel(Deflater.BEST_COMPRESSION);

        FileInputStream fis = new FileInputStream("file1.txt");
        byte[] buffer = new byte[1024];
        ZipEntry entry = new ZipEntry("file1.txt");
        zos.putNextEntry(entry);

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

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

위의 예제 코드에서 ZipOutputStreamsetLevel 메서드를 사용하여 압축 수준을 설정할 수 있습니다. Deflater 클래스의 상수를 사용하여 압축 수준을 지정할 수 있습니다. 여기서는 BEST_COMPRESSION을 사용하여 최상의 압축 수준을 설정했습니다.

참고 자료