[java] 자바에서 압축 파일의 크기를 줄이는 방법
압축 파일은 파일이나 디렉토리를 하나의 파일로 묶어서 저장하는 방식입니다. 자바에서는 java.util.zip
패키지를 사용하여 압축 파일을 생성하고, 크기를 줄이는 방법을 제공합니다.
1. ZipOutputStream
을 사용하여 압축 파일 생성하기
ZipOutputStream
클래스는 압축 파일을 생성하기 위한 클래스입니다. 다음은 ZipOutputStream
을 사용하여 압축 파일을 생성하는 예제 코드입니다.
import java.io.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class ZipExample {
public static void main(String[] args) {
String sourceFile = "path/to/source/file.txt";
String zipFile = "path/to/zip/file.zip";
try {
FileOutputStream fos = new FileOutputStream(zipFile);
ZipOutputStream zos = new ZipOutputStream(fos);
File file = new File(sourceFile);
// 압축 파일에 추가할 엔트리 생성
ZipEntry zipEntry = new ZipEntry(file.getName());
zos.putNextEntry(zipEntry);
FileInputStream fis = new FileInputStream(file);
byte[] buffer = new byte[1024];
int length;
while ((length = fis.read(buffer)) > 0) {
zos.write(buffer, 0, length);
}
// 스트림 닫기
fis.close();
zos.closeEntry();
zos.close();
System.out.println("압축 파일 생성 완료.");
} catch (IOException e) {
e.printStackTrace();
}
}
}
위의 예제 코드에서 ZipOutputStream
을 사용하여 압축 파일을 생성합니다. 원본 파일은 FileInputStream
을 사용하여 읽어오고, ZipOutputStream
으로 쓰여진 데이터를 압축합니다.
2. 압축 파일 크기를 줄이는 방법
압축 파일의 크기를 줄이는 방법은 크게 두 가지로 나뉩니다.
2.1. 압축 레벨 설정하기
압축 파일 생성 시 사용되는 압축 레벨은 0부터 9까지의 값을 가지며, 기본값은 8입니다. 압축 레벨이 높을수록 압축률은 높아지지만, 압축 속도는 느려집니다. 다음은 압축 레벨을 설정하는 예제 코드입니다.
zos.setLevel(9); // 압축 레벨을 9로 설정
2.2. 중복 파일 제거하기
압축 파일에는 동일한 파일이 중복으로 포함될 수 있습니다. 중복 파일을 제거하여 압축 파일의 크기를 줄일 수 있습니다. 다음은 중복 파일을 제거하는 예제 코드입니다.
HashSet<String> fileNames = new HashSet<>();
// 중복 파일 제거
for (String fileName : fileNames) {
ZipEntry entry = new ZipEntry(fileName);
zos.putNextEntry(entry);
FileInputStream fileInputStream = new FileInputStream(new File(fileName));
byte[] buffer = new byte[1024];
int length;
while ((length = fileInputStream.read(buffer)) > 0) {
zos.write(buffer, 0, length);
}
fileInputStream.close();
zos.closeEntry();
}
위의 예제 코드에서는 중복 파일을 제거하기 위해 HashSet을 사용하여 파일 이름을 중복 없이 관리합니다. 중복 파일을 처리할 때는 ZipOutputStream
의 putNextEntry
메서드를 호출하여 새로운 엔트리를 추가하고, 중복 파일의 내용을 작성합니다.