2026년 1월 13일 화요일

lz4 압출 해제

 import net.jpountz.lz4.*;

import java.io.*;

import java.nio.ByteBuffer;

import java.nio.charset.StandardCharsets;


public class Lz4LineProcessor {

    // LZ4Factory는 Thread-safe하며 재사용 가능합니다.

    private static final LZ4Factory factory = LZ4Factory.fastestInstance();

    private static final LZ4Compressor compressor = factory.fastCompressor();

    private static final LZ4SafeDecompressor decompressor = factory.safeDecompressor();


    /**

     * 파일을 읽어 라인별로 압축하여 저장

     */

    public void compressLineByLine(String inputPath, String outputPath) throws IOException {

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

             DataOutputStream dos = new DataOutputStream(new FileOutputStream(outputPath))) {


            String line;

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

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

                int maxLen = compressor.maxCompressedLength(data.length);

                byte[] compressed = new byte[maxLen];

                

                // 압축 수행

                int compressedLen = compressor.compress(data, 0, data.length, compressed, 0, maxLen);


                // [원본길이(4바이트)][압축길이(4바이트)][압축데이터] 구조로 기록

                dos.writeInt(data.length);

                dos.writeInt(compressedLen);

                dos.write(compressed, 0, compressedLen);

            }

        }

    }


    /**

     * 압축된 파일을 읽어 한 라인씩 해제

     */

    public void decompressLineByLine(String inputPath) throws IOException {

        try (DataInputStream dis = new DataInputStream(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 = new byte[originalLen];

                decompressor.decompress(compressed, 0, compressedLen, decompressed, 0, originalLen);


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

                // 여기서 line 처리 (예: 출력 또는 리스트 담기)

                // System.out.println(line); 

            }

        }

    }

}


댓글 없음: