[java] 자바에서 압축 해제 시 파일 권한 설정하기

다음은 java.util.zip 패키지를 사용하여 zip 파일을 압축 해제하고 파일 권한을 설정하는 방법입니다.

import java.io.*;
import java.nio.file.*;
import java.util.zip.*;

public class ZipExtractor {
    public static void extractAndSetPermissions(String zipFilePath, String destinationPath) throws IOException {
        byte[] buffer = new byte[1024];
        File folder = new File(destinationPath);
        if (!folder.exists()) {
            folder.mkdirs();
        }
        ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFilePath));
        ZipEntry entry = zis.getNextEntry();
        while (entry != null) {
            String fileName = entry.getName();
            File newFile = new File(destinationPath + File.separator + fileName);
            if (entry.isDirectory()) {
                newFile.mkdirs();
            } 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();

                // 파일 권한 설정 예시
                Path filePath = Paths.get(newFile.getAbsolutePath());
                Files.setPosixFilePermissions(filePath, PosixFilePermissions.fromString("rwxrwxrwx"));
            }
            zis.closeEntry();
            entry = zis.getNextEntry();
        }
        zis.closeEntry();
        zis.close();
    }
}

위의 코드에서 Files.setPosixFilePermissions를 사용하여 파일의 권한을 설정하고 있습니다. 이 코드를 활용하여 파일을 압축 해제하고 원하는 파일 권한을 설정할 수 있습니다.

이 코드는 Java 7 이상에서 사용할 수 있습니다.

참고문헌: