[java] 자바에서 압축 파일을 해제할 때 충돌 방지하기

파일을 압축 해제할 때, 동일한 이름을 가진 파일이 이미 존재할 경우 충돌이 발생할 수 있습니다. 그러나 자바에서는 이런 충돌을 방지하기 위한 방법을 제공하고 있습니다. 이번 글에서는 자바에서 압축 파일을 해제할 때 충돌을 방지하기 위한 방법에 대해 알아보겠습니다.

압축 파일 해제

먼저, 압축 파일을 해제하는 방법을 알아보겠습니다. 자바에서는 java.util.zip 패키지의 ZipFile 또는 ZipInputStream 클래스를 사용하여 압축 파일을 해제할 수 있습니다. 아래는 ZipInputStream을 사용한 예제 코드입니다.

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

public class UnzipExample {
    public static void main(String[] args) throws IOException {
        String zipFilePath = "path/to/your/zipfile.zip";
        String destDir = "path/to/your/destination/folder/";        
        byte[] buffer = new byte[1024];
        
        try (ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFilePath))) {
            ZipEntry zipEntry = zis.getNextEntry();
            
            while (zipEntry != null) {
                String fileName = zipEntry.getName();
                File newFile = new File(destDir + File.separator + fileName);
                
                new File(newFile.getParent()).mkdirs();
                
                try (FileOutputStream fos = new FileOutputStream(newFile)) {
                    int len;
                    while ((len = zis.read(buffer)) > 0) {
                        fos.write(buffer, 0, len);
                    }
                }
                
                zipEntry = zis.getNextEntry();
            }
        }
    }
}

위의 코드는 ZipInputStream을 사용하여 압축 파일을 해제하는 예제입니다.

충돌 방지

이제 같은 이름의 파일이 이미 존재할 경우 충돌을 방지하는 방법에 대해 알아보겠습니다. 충돌을 방지하려면 압축 파일의 각 파일을 해제하기 전에 해당 파일이 이미 존재하는지 확인해야 합니다. 아래는 파일 충돌을 방지하기 위한 예제 코드입니다.

// 위의 UnzipExample 클래스 내에 추가하여 사용
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

ZipEntry zipEntry = zis.getNextEntry();
while (zipEntry != null) {
    String fileName = zipEntry.getName();
    File newFile = new File(destDir + File.separator + fileName);
    
    if (newFile.exists()) {
        // 파일이 이미 존재하는 경우 처리
        Path path = Paths.get(destDir + File.separator + fileName);
        String fileNameWithoutExt = fileName.replaceFirst("[.][^.]+$", "");
        String fileExtension = fileName.substring(fileName.lastIndexOf(".") + 1);
        int count = 1;

        while (Files.exists(path)) {
            String newFileName = fileNameWithoutExt + "_" + count + "." + fileExtension;
            path = Paths.get(destDir + File.separator + newFileName);
            count++;
        }

        newFile = new File(path.toString());
    }
    
    // 파일 저장 로직
    // ...
    
    zipEntry = zis.getNextEntry();
}

위의 코드는 압축 파일을 해제하면서 파일 이름 충돌을 방지하는 예제입니다. 이미 존재하는 파일인 경우, 파일 이름을 변경하여 충돌을 방지합니다.

압축 파일을 해제하면서 충돌을 방지하는 방법에 대해 알아보았습니다. 이를 통해 안전하게 파일을 압축 해제할 수 있고, 이미 존재하는 파일과 충돌하는 문제를 방지할 수 있습니다.

참고 자료