tags:

views:

646

answers:

2

Using Java how could I manipulate the access permissions of a file in Windows?

+6  A: 

If you are using Java 6, File class gives you setExecutable, setWritable, etc. See: http://java.sun.com/javase/6/docs/api/java/io/File.html

On older Java versions this is not possible; you have to exec OS commands to do that:

Windows: Runtime.getRuntime().exec("attrib -r myFile");

Unix: Runtime.getRuntime().exec("chmod 777 myFile");

Zed
+1 I didn't know about the new methods in java6
skaffman
chmod won't work in windows, attrib -R or +R will change the read-only flag
Rich Seller
You may want to be a bit more restrictive with the Unix permissioning, btw. 777 gives everyone everything :-)
Brian Agnew
Obviously, 777 was an example. If another question is asked on how to use chmod or attrib, I'm more than happy to answer ;)
Zed
@Rich: Instead of `attrib` on Windows you probably want to use `cacls`. `cacls /?` in a command prompt for more information.
Grant Wagner
+1  A: 

The new Java 7 java.nio.file.attribute package will make all of this a lot easier. It provides views onto the complete set of file attributes, including Posix file permissions.

Obviously not released yet, but perhaps worth thinking about if you have to do this at lot (at least worth abstracting out your permissioning code to cater for this going forward)

Brian Agnew