Skip to main content

NIO2: Generic method to set file readonly ?

Please note these forums are being decommissioned and use the new and improved forums at
2 replies [Last post]
Joined: 2009-09-09

I am looking for a standard and portable way to set file readonly using the Path API.
Using the XxxAttributes classes, I can access to the details of the FileSystem, but the portable attributes of BasicFileAttributeView are rather limited. There is no equivalent for the File.setReadOnly() method.
I have two solutions:

  • Using the old File API:
  • Path path=...
    new File(path.toString()).setReadOnly()
  • Writing a complex method that try to:
  1. use the DOSFileAttributeView (available only on Windows)
  2. use the PosixFileAttributeView (not available on Windows)
  3. and ultimately the ACLFileAttributeView (not available on Linux (maybe because I am missing the acl package)).

Where is the "Write Once, Run Anywhere"?
Emmanuel CASTRO
Montigny le Bretonneux

Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
Joined: 2005-08-08

The new file system API supports the two common security models so you have APIs to edit file permissions or ACLs. This is something that has been eagerly sought for a long time.
We don't have "high level" methods, which I think is what you are looking for. It's not always clear that there is a good mapping but maybe something that you should bring up on the nio-dev mailing list.

Joined: 2009-09-09

I imagine the following methods can be useful:

  • trySetReadOnly() take a boolean and makes its best effort to prevent/allow the file/directory to be written.
    • It returns the state that could actually be set (see below isReadOnly). Throwing an exception or not is very business logic dependent, I think it should fail silently.
    • On DOS : just put the readOnly flag
    • On Posix : try chmod -w
    • On ACL : try to remove the WRITE_DATA on each entry (I don't know how it behaves when one has right on some entries but not all).
  • isReadOnly() is more complex.
    • A first level of details gives the tri-state values (true, false, readOnlyForSome)
    • A finer level of details gives a POSIX like set of 'bits' ('CurrentUser' : true/false, 'Owner' : true/false, 'Other' : none/some/all).
    • On DOS : the only readable values are true and false, and all the 'bits' have the same value.
    • On Posix : depending on who is the current user, the set above is calculated.
    • On ACL : the ACL entries are sorted into 3 categories: 'CurrentUser', 'Owner', 'Other'. I think that for the two first categories, there is only one relevant ACL entry yielding to values for the bits.
      For the 'Other' category, we get none, some or all.

I don't know if it is possible/easy to add new AttributeView to standard files.