import net.jpountz.lz4.*;
import java.io.*;
import java.nio.charset.StandardCharsets;
public class Lz4FileProcessor {
private static final LZ4Factory factory = LZ4Factory.fastestInstance();
private static final LZ4Compressor compressor = factory.fastCompressor();
private static final LZ4SafeDecompressor decompressor = factory.safeDecompressor();
/**
* 파일을 읽어 라인별로 LZ4 압축하여 저장 (기존 파일 초기화)
*/
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);
int maxLen = compressor.maxCompressedLength(data.length);
byte[] compressed = new byte[maxLen];
// 실제 압축된 길이 반환
int compressedLen = compressor.compress(data, 0, data.length, compressed, 0, maxLen);
// [원본길이][압축데이터길이][압축데이터] 순으로 기록
dos.writeInt(data.length);
dos.writeInt(compressedLen);
dos.write(compressed, 0, compressedLen);
}
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* LZ4로 압축된 파일을 읽어 라인별로 해제
*/
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 = new byte[originalLen];
// 압축 해제 수행
decompressor.decompress(compressed, 0, compressedLen, decompressed, 0, originalLen);
String line = new String(decompressed, StandardCharsets.UTF_8);
// 비즈니스 로직 수행 (예: 로그 분석 등)
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
댓글 없음:
댓글 쓰기