import com.github.luben.zstd.Zstd;
import java.io.*;
import java.nio.charset.StandardCharsets;
public class ZstdLineProcessor {
/**
* 파일을 읽어 라인별로 Zstd 압축하여 저장
*/
public void compressLineByLine(String inputPath, String outputPath) throws IOException {
// BufferedStream으로 감싸서 디스크 I/O 성능 최적화
try (BufferedReader reader = new BufferedReader(new FileReader(inputPath));
DataOutputStream dos = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(outputPath)))) {
String line;
while ((line = reader.readLine()) != null) {
byte[] data = line.getBytes(StandardCharsets.UTF_8);
// Zstd 압축 수행 (압축 레벨은 보통 3이 기본이며 성능과 압축률의 균형이 좋음)
byte[] compressed = Zstd.compress(data, 3);
// [원본길이(4바이트)][압축데이터길이(4바이트)][압축데이터] 순으로 기록
dos.writeInt(data.length);
dos.writeInt(compressed.length);
dos.write(compressed);
}
dos.flush();
}
}
/**
* Zstd로 압축된 파일을 읽어 한 라인씩 해제
*/
public void decompressLineByLine(String inputPath) throws IOException {
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);
// 원본 길이를 알고 있으므로 decompress 메서드를 바로 사용
byte[] decompressed = Zstd.decompress(compressed, originalLen);
String line = new String(decompressed, StandardCharsets.UTF_8);
// 비즈니스 로직 수행 (예: 출력 등)
// System.out.println(line);
}
}
}
}
댓글 없음:
댓글 쓰기