[java] Gzip 압축 알고리즘을 자바에서 사용하는 방법

Gzip은 디스크 공간을 절약하거나 데이터를 효율적으로 전송하기 위해 사용되는 압축 알고리즘입니다. 이 알고리즘을 자바에서 사용하기 위해서는 몇 가지 단계를 거쳐야 합니다. 아래에서 자세히 알아보겠습니다.

1. Gzip 클래스 임포트하기

먼저 Gzip 클래스를 사용하기 위해 해당 클래스를 자바 코드에 임포트해야 합니다.

import java.util.zip.GZIPOutputStream;

2. 데이터를 압축하기

Gzip 알고리즘을 사용하여 데이터를 압축하려면 원본 데이터를 GZIPOutputStream으로 전달해야 합니다. 압축 된 데이터는 출력 스트림에 기록됩니다. 아래 코드는 작성된 데이터를 Gzipped 파일로 압축하는 예시입니다.

String input = "Hello, World!";
byte[] inputData = input.getBytes("UTF-8");

try (FileOutputStream fileOutputStream = new FileOutputStream("compressed.gz");
     GZIPOutputStream gzipOutputStream = new GZIPOutputStream(fileOutputStream)) {
    gzipOutputStream.write(inputData);
    gzipOutputStream.close();
} catch (IOException e) {
    e.printStackTrace();
}

위의 코드에서는 GZIPOutputStreamFileOutputStream에 연결하고, write() 메서드를 사용하여 데이터를 압축하여 파일에 기록합니다. 압축된 파일은 “compressed.gz”라는 이름으로 생성됩니다.

3. 압축 해제

Gzip 압축을 해제하기 위해서는 GZIPInputStream 클래스를 사용해야 합니다. 아래 코드는 Gzipped 파일을 읽고 압축을 해제하는 예시입니다.

try (FileInputStream fileInputStream = new FileInputStream("compressed.gz");
     GZIPInputStream gzipInputStream = new GZIPInputStream(fileInputStream)) {
    byte[] buffer = new byte[1024];
    int bytesRead;

    while ((bytesRead = gzipInputStream.read(buffer)) > 0) {
        // 압축 해제 된 데이터를 처리하는 로직
        String decompressedData = new String(buffer, 0, bytesRead, "UTF-8");
        System.out.println("Decompressed Data: " + decompressedData);
    }

    gzipInputStream.close();
} catch (IOException e) {
    e.printStackTrace();
}

위의 코드에서는 GZIPInputStreamFileInputStream에 연결하고 read() 메서드를 사용하여 압축 해제 된 데이터를 읽습니다. 압축 해제 된 데이터는 decompressedData 변수에 저장되어 처리할 수 있습니다.

결론

이러한 단계들을 따라서 Gzip 압축 알고리즘을 자바에서 사용할 수 있습니다. Gzip은 데이터 압축 및 전송에 널리 사용되는 강력한 알고리즘이므로, 다양한 시나리오에서 유용하게 활용할 수 있습니다.

참고 자료