import java.io.*;
import java.util.zip.*;
import java.nio.charset.StandardCharsets;
public class DeflaterProcessor {
/**
* 파일을 읽어 라인별로 Deflater 압축하여 저장
*/
public void compressFile(String inputPath, String outputPath) {
// 'false'로 설정하여 기존 파일이 있으면 내용을 지우고 새로 생성
try (BufferedReader reader = new BufferedReader(new FileReader(inputPath));
DataOutputStream dos = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(outputPath, false)))) {
String line;
Deflater deflater = new Deflater();
byte[] buffer = new byte[1024];
while ((line = reader.readLine()) != null) {
byte[] data = line.getBytes(StandardCharsets.UTF_8);
deflater.setInput(data);
deflater.finish();
// 압축 수행 및 결과물을 임시로 담을 바이트 배열 생성
ByteArrayOutputStream baos = new ByteArrayOutputStream();
while (!deflater.finished()) {
int count = deflater.deflate(buffer);
baos.write(buffer, 0, count);
}
deflater.reset();
byte[] compressedData = baos.toByteArray();
// [원본길이][압축데이터길이][압축데이터] 순으로 저장
dos.writeInt(data.length);
dos.writeInt(compressedData.length);
dos.write(compressedData);
}
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 압축된 파일을 읽어 라인별로 Inflater 해제
*/
public void decompressFile(String inputPath) {
try (DataInputStream dis = new DataInputStream(new BufferedInputStream(new FileInputStream(inputPath)))) {
Inflater inflater = new Inflater();
while (dis.available() > 0) {
int originalLen = dis.readInt();
int compressedLen = dis.readInt();
byte[] compressedData = new byte[compressedLen];
dis.readFully(compressedData);
byte[] decompressedData = new byte[originalLen];
inflater.setInput(compressedData);
inflater.inflate(decompressedData);
inflater.reset();
String line = new String(decompressedData, StandardCharsets.UTF_8);
// System.out.println(line); // 복구된 라인 출력
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
댓글 없음:
댓글 쓰기