views:

2883

answers:

2

In java, i'm dynamically creating a set of files and i'd like to change the file permissions on these files on a linux/unix file system. I'd like to be able to execute the java equivalent of chmod. Is that possible Java 5, if so, how?

I know in Java 6 the File object has setReadable()/setWritable() methods. I also know i could make a system call to do this, but i'd like to avoid that if possible.

+6  A: 

Unfortunately, full control over file attributes will not be available until Java 7, as part of the "new" New IO facility (NIO.2). Pre-release versions are available in the OpenJDK project.

Until then, using native code of your own, or exec-ing command-line utilities are common approaches.

erickson
selecting this one as I don't have the ability to use Marty Lamb's answer.
Roy Rico
I seriously cannot believe that it's been over six years since they started working on NIO.2 and it's still not in a shipping JRE.
clee
Yes, it's been a long time in coming.
erickson
+8  A: 

In addition to erickson's suggestions, there's also jna, which allows you to call native libraries without using jni. It's shockingly easy to use, and I've used it on a couple of projects with great success.

The only caveat is that it's slower than jni, so if you're doing this to a very large number of files that might be an issue for you.

(Editing to add example)

Here's a complete jna chmod example:

import com.sun.jna.Library;
import com.sun.jna.Native;

public class Main {
    private static CLibrary libc = (CLibrary) Native.loadLibrary("c", CLibrary.class);

    public static void main(String[] args) {
        libc.chmod("/path/to/file", 0755);
    }
}

interface CLibrary extends Library {
    public int chmod(String path, int mode);
}
Marty Lamb
Thanks for the example
Roy Rico
JNA is such a nice tool for native calls!
erickson