Tuesday, 27 November 2012

UNIX File Permissions for Java 7's java.nio.file Package

During a recent project at work, I found myself needing the ability to work with UNIX specific file permissions with Java 7's java.nio.file package, but unfortunately it's not trivial to do so. The package currently provides functionality to get and set POSIX file permissions, but these file permissions do not include certain permissions such as setting the GID or UID bit.

Because it wasn't trivial to work with UNIX specific file permissions, I've created a quick project to do just that. The project includes a UnixFiles class, which attempts to mimic as closely as possible the current functionality of getting and setting POSIX file permissions. There is also functionality to check whether a supplied FileSystem supports UNIX file permissions, and methods to easily move backwards and forwards between UNIX and POSIX file permissions to try and aid with writing code that can run on any OS (well, one which at least supports POSIX file permissions).

Okay, quick code example to show how to use it:

Path path = Paths.get("/home/adam/test.txt");
Set<UnixFilePermission> perms = 
        UnixFilePermissions.parseMode("777", 8);
if (UnixFiles.hasUnixFilePermissions(path.getFileSystem())) {
    UnixFiles.setUnixFilePermissions(path, perms);
else {

As you can see, I've added functionality to move between a "mode" and the set of file permissions. In the example, I used the octal permissions 777, which are -rwxrwxrwx. If we were to print out the set of file permissions returned from the parseMode method, we would see the following:


So, you can get this project from my github. All feedback, pull requests, bug reports, etc, are welcome.

No comments:

Post a Comment