2026년 1월 13일 화요일

z standard 압축해제

 import com.github.luben.zstd.Zstd;

import java.io.*;

import java.nio.charset.StandardCharsets;


public class ZstdFileProcessor {


    /**

     * 파일을 읽어 라인별로 Zstd 압축하여 저장 (기존 파일 초기화)

     */

    public void compressFile(String inputPath, String outputPath) {

        try (BufferedReader reader = new BufferedReader(new FileReader(inputPath));

             DataOutputStream dos = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(outputPath, false)))) {


            String line;

            while ((line = reader.readLine()) != null) {

                byte[] data = line.getBytes(StandardCharsets.UTF_8);

                

                // Zstd.compress()는 기본 압축 레벨 3을 사용하며, 속도와 압축률의 균형이 가장 좋습니다.

                byte[] compressed = Zstd.compress(data);


                // [원본길이][압축데이터길이][압축데이터] 순으로 기록

                dos.writeInt(data.length);

                dos.writeInt(compressed.length);

                dos.write(compressed);

            }

        } catch (IOException e) {

            e.printStackTrace();

        }

    }


    /**

     * Zstd로 압축된 파일을 읽어 라인별로 해제

     */

    public void decompressFile(String inputPath) {

        try (DataInputStream dis = new DataInputStream(new BufferedInputStream(new FileInputStream(inputPath)))) {

            while (dis.available() > 0) {

                int originalLen = dis.readInt();

                int compressedLen = dis.readInt();


                byte[] compressed = new byte[compressedLen];

                dis.readFully(compressed);


                // 원본 길이를 알고 있으므로 정확한 크기의 버퍼로 바로 해제 (가장 빠른 방식)

                byte[] decompressed = Zstd.decompress(compressed, originalLen);


                String line = new String(decompressed, StandardCharsets.UTF_8);

                // 비즈니스 로직 수행

            }

        } catch (IOException e) {

            e.printStackTrace();

        }

    }

}


댓글 없음: