[java] 자바에서 압축 파일에 중복 파일 제거하기
목차
- 필요한 라이브러리 추가
- 중복 파일 제거하는 메서드 구현
- 예제 코드
- 마무리
1. 필요한 라이브러리 추가
먼저 Maven 또는 Gradle과 같은 빌드 도구를 사용하여 프로젝트에 Apache Commons Compress 라이브러리를 추가해야 합니다.
Maven:
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-compress</artifactId>
<version>1.21</version>
</dependency>
Gradle:
implementation 'org.apache.commons:commons-compress:1.21'
2. 중복 파일 제거하는 메서드 구현
압축 파일에서 중복 파일을 제거하는 메서드는 다음과 같이 구현할 수 있습니다.
import org.apache.commons.compress.archivers.ArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveInputStream;
import org.apache.commons.compress.archivers.zip.ZipFile;
import org.apache.commons.compress.utils.IOUtils;
import java.io.*;
import java.util.HashSet;
import java.util.Set;
public class ZipUtil {
public static void removeDuplicateFiles(String zipFilePath, String outputZipFilePath) throws IOException {
Set<String> fileNames = new HashSet<>();
try (ZipFile zipFile = new ZipFile(zipFilePath)) {
try (ZipArchiveInputStream zipInput = new ZipArchiveInputStream(new BufferedInputStream(new FileInputStream(zipFilePath)))) {
ArchiveEntry entry;
while ((entry = zipInput.getNextEntry()) != null) {
if (!entry.isDirectory() && fileNames.add(entry.getName())) {
try (OutputStream output = new FileOutputStream(outputZipFilePath)) {
IOUtils.copy(zipInput, output);
}
}
}
}
}
}
}
3. 예제 코드
아래는 ZipUtil
클래스를 사용하여 압축 파일에서 중복 파일을 제거하는 예제 코드입니다.
public class Main {
public static void main(String[] args) {
String inputZipFile = "input.zip";
String outputZipFile = "output.zip";
try {
ZipUtil.removeDuplicateFiles(inputZipFile, outputZipFile);
System.out.println("중복 파일 제거 완료");
} catch (IOException e) {
e.printStackTrace();
}
}
}
4. 마무리
이제 자바를 사용하여 압축 파일에서 중복 파일을 제거하는 방법에 대해 알아보았습니다. 이를 통해 파일 시스템을 깔끔하게 유지할 수 있으며 효율적인 파일 관리가 가능합니다.
참고 문헌:
샘플 코드를 참고하셔서 프로젝트에 맞게 수정하여 사용해보시기 바랍니다.