[java] 자바에서 압축 해제 후 기존 파일 유지하기
  1. 압축 파일 해제하기

    먼저, 아래와 같이 java.util.zip.ZipInputStream을 사용하여 압축 파일을 해제할 수 있습니다.

    import java.io.*;
    import java.util.zip.*;
    
    public class ZipFileExtractor {
        public static void extract(String zipFilePath, String destFolderPath) throws IOException {
            try (ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(zipFilePath))) {
                ZipEntry entry;
                while ((entry = zipInputStream.getNextEntry()) != null) {
                    String entryName = entry.getName();
                    File destFile = new File(destFolderPath + File.separator + entryName);
       
                    if (entry.isDirectory()) {
                        destFile.mkdirs();
                    } else {
                        byte[] buffer = new byte[1024];
                        try (FileOutputStream fos = new FileOutputStream(destFile); BufferedOutputStream bos = new BufferedOutputStream(fos, buffer.length)) {
                            int read;
                            while ((read = zipInputStream.read(buffer, 0, buffer.length)) != -1) {
                                bos.write(buffer, 0, read);
                            }
                        } 
                    }
                }
            }
        }
    }
    

    위 코드는 압축 파일을 해제하여 기존 파일을 덮어쓰지 않고 해당 파일을 유지합니다.

  2. 파일 존재 확인하기

    압축 해제하기 전에 이미 파일이 존재하는지 확인하여 덮어쓰지 않도록 조치할 수 있습니다.

    // 파일 존재 확인
    File existingFile = new File(destFolderPath + File.separator + entryName);
    if (existingFile.exists()) {
        throw new IOException("File already exists: " + existingFile);
    }
    

    위 코드를 사용하여 해당 파일이 이미 존재하는지 확인하고, 이미 존재한다면 예외를 발생시켜 처리할 수 있습니다.

이렇게 하면 자바에서 압축 파일을 해제한 후 기존 파일을 유지할 수 있습니다.