18

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

David Webb
  • 190,537
  • 57
  • 313
  • 299
anoop john
  • 211
  • 1
  • 5
  • 6

2 Answers2

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
  • 14
    On Windows 7 attempting to get Posix attributes throws UnsupportedOperationException. – gerardw May 20 '15 at 12:06
  • 4
    How 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
  • 1
    This 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