Using Java how could I manipulate the access permissions of a file in Windows?
Asked
Active
Viewed 1.7k times
2 Answers
20
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");

Brian Agnew
- 268,207
- 37
- 334
- 440

Zed
- 57,028
- 9
- 76
- 100
-
chmod won't work in windows, attrib -R or +R will change the read-only flag – Rich Seller Jul 29 '09 at 07:30
-
You may want to be a bit more restrictive with the Unix permissioning, btw. 777 gives everyone everything :-) – Brian Agnew Jul 29 '09 at 08:37
-
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 Jul 29 '09 at 09:03
-
1@Rich: Instead of `attrib` on Windows you probably want to use `cacls`. `cacls /?` in a command prompt for more information. – Grant Wagner Jul 29 '09 at 21:23
10
The new Java 7 java.nio.file.attribute package makes all of this a lot easier. It provides views onto the complete set of file attributes, including Posix file permissions.

dpr
- 10,591
- 3
- 41
- 71

Brian Agnew
- 268,207
- 37
- 334
- 440
-
14On Windows 7 attempting to get Posix attributes throws UnsupportedOperationException. – gerardw May 20 '15 at 12:06
-
4How do we go about solving the problem in windows without having to run a command? Is there a common library that we can use to set permissions on all operating systems? – saibharath Oct 16 '15 at 19:01
-
1This answer is a little bit short, but the java.nio.file.attribute package includes also ACL handling for Windows! – Mayra Delgado Jul 19 '17 at 12:37