[java] 자바 소켓 프로그래밍을 통한 데이터 압축과 압축 해제

이번 포스트에서는 자바 소켓 프로그래밍을 사용하여 데이터를 압축하고 압축 해제하는 방법에 대해 알아보겠습니다.

압축 알고리즘 선택

데이터를 압축하려면 압축 알고리즘을 선택해야 합니다. 자바에서는 여러 가지 압축 알고리즘을 지원합니다. 대표적으로 gzip과 zip 압축 알고리즘이 있습니다.

다음은 gzip 압축 알고리즘을 사용하는 예제 코드입니다.

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

public class FileCompressor {

    public static void compressFile(File inputFile, File outputFile) throws IOException {
        try (FileInputStream fis = new FileInputStream(inputFile);
             FileOutputStream fos = new FileOutputStream(outputFile);
             GZIPOutputStream gzos = new GZIPOutputStream(fos)) {
            
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = fis.read(buffer)) != -1) {
                gzos.write(buffer, 0, bytesRead);
            }
        }
    }

    public static void main(String[] args) {
        File inputFile = new File("input.txt");
        File outputFile = new File("compressed.gz");

        try {
            compressFile(inputFile, outputFile);
            System.out.println("File compressed successfully.");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

위의 예제 코드는 FileCompressor 클래스에서 compressFile 메서드를 사용하여 파일을 압축하는 기능을 제공합니다. 입력 파일과 출력 파일 경로를 인수로 받아 GZIPOutputStream을 사용하여 데이터를 압축합니다.

압축 해제

이제 데이터를 압축 해제하는 방법에 대해 살펴보겠습니다. gzip 압축 해제를 위해서는 GZIPInputStream을 사용해야 합니다.

다음은 gzip 압축 해제를 위한 예제 코드입니다.

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

public class FileDecompressor {

    public static void decompressFile(File inputFile, File outputFile) throws IOException {
        try (FileInputStream fis = new FileInputStream(inputFile);
             GZIPInputStream gzis = new GZIPInputStream(fis);
             FileOutputStream fos = new FileOutputStream(outputFile)) {

            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = gzis.read(buffer)) != -1) {
                fos.write(buffer, 0, bytesRead);
            }
        }
    }

    public static void main(String[] args) {
        File inputFile = new File("compressed.gz");
        File outputFile = new File("output.txt");

        try {
            decompressFile(inputFile, outputFile);
            System.out.println("File decompressed successfully.");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

위의 예제 코드는 FileDecompressor 클래스에서 decompressFile 메서드를 사용하여 압축 파일을 해제하는 기능을 제공합니다. 입력 파일과 출력 파일 경로를 인수로 받아 GZIPInputStream을 사용하여 데이터를 압축 해제합니다.

결론

이번 포스트에서는 자바 소켓 프로그래밍을 사용하여 데이터를 압축하고 압축 해제하는 방법에 대해 알아보았습니다. gzip 압축 알고리즘을 사용하여 데이터를 압축하고, GZIPInputStream을 사용하여 압축을 해제할 수 있습니다. 데이터 압축은 네트워크 전송 시 대역폭을 절약하고 데이터 전송 속도를 향상시킬 수 있는 효과적인 방법입니다.