[java] ZIP 압축 방법을 사용하여 압축 파일을 해제하는 코드 예제

다음은 java.util.zip 패키지를 사용하여 ZIP 파일을 압축 해제하는 Java 코드의 예제입니다.

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

public class ZipExtractor {

    public static void main(String[] args) {
        String zipFilePath = "path/to/your/zipfile.zip";
        String destDir = "path/to/extract/destination";

        try {
            unzip(zipFilePath, destDir);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void unzip(String zipFilePath, String destDir) throws IOException {
        File destDirectory = new File(destDir);
        if (!destDirectory.exists()) {
            destDirectory.mkdir();
        }
        byte[] buffer = new byte[1024];
        ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFilePath));
        ZipEntry zipEntry = zis.getNextEntry();

        while (zipEntry != null) {
            File newFile = newFile(destDirectory, zipEntry);
            if (zipEntry.isDirectory()) {
                newFile.mkdir();
            } else {
                new File(newFile.getParent()).mkdirs();
                FileOutputStream fos = new FileOutputStream(newFile);
                int len;
                while ((len = zis.read(buffer)) > 0) {
                    fos.write(buffer, 0, len);
                }
                fos.close();
            }
            zipEntry = zis.getNextEntry();
        }
        zis.closeEntry();
        zis.close();
    }

    private static File newFile(File destinationDir, ZipEntry zipEntry) throws IOException {
        File destFile = new File(destinationDir, zipEntry.getName());
        String destDirPath = destinationDir.getCanonicalPath();
        String destFilePath = destFile.getCanonicalPath();
        if (!destFilePath.startsWith(destDirPath + File.separator)) {
            throw new IOException("Entry is outside of the target dir: " + zipEntry.getName());
        }
        return destFile;
    }
}

위의 코드는 java.util.zip.ZipInputStream 클래스를 사용하여 ZIP 파일을 압축 해제하는 방법을 보여줍니다. 코드를 실행하면 지정된 디렉토리에 ZIP 파일이 압축 해제됩니다.

참고로 위의 코드는 예제일 뿐이며, 실제 사용 시에는 예외 처리와 리소스 관리를 추가하는 것이 좋습니다.

기타 참고 자료: