Maintain file permissions when extracting from a zip file using JDK 5 api
I think it is actually impossible to keep the permissions correctly.
Permissions are very OS specific: while POSIX file permissions allow the user to set whether you can read, write or execute a file for the file owner, the group and others, the NTFS file system has a similar system but the concept for an execute permission is inexistant. And the early FAT/FAT32 file syste, do not have file permissions at all (a part from the read-only attribute).
Being cross-platform, it would be difficult for java to set the permission properly on the newly created (unzipped) files depending on the underlying OS....
That said, Java 6 has a new java.io.File class that allows you to set permissions (with methods like setExecutable(), setReadable(), etc...)
These helped me a lot, especially the setExecutable() which was my main concerned when having to unzip executables on a Linux file system. And you don't have to bother about figuring out what OS you are running on as the method will simply do nothing if running under Windows or other systems without the concept of executable files.
The unix permissions are stored in the zip, either in the entry external attributes, or in the extra fields (using the "Asi" extra field, tagged with the 0x756E id). java.util.zip.ZipEntry
exposes the extra fields and the Asi field could be read if there is one, but the external attributes are not accessible. So it's not possible to restore the files permissions in all cases using only the JDK zip implementation.
Fortunately the Apache Commons Compress project has its own ZipFile implementation which parses the external attributes, the permissions are exposed with the ZipArchiveEntry.getUnixMode() method. Then with Ant's PermissionUtils class and the Java NIO API, the permissions can be applied back to the file extracted with:
Files.setPosixFilePermissions(path, PermissionUtils.permissionsFromMode(entry.getUnixMode()));