2

I would like to get permissions of a file for a specific user. Currently I was doing something like this:

 File file1 = new File(filePath);
 System.out.println("write permissions: " + file1.canWrite);
 //and other attributes

This provides permission of user executing the program. But the problem is that I would like to specify a user or at least print all permissions of the file, not only for all users. Any ideas?

Xolve
  • 22,298
  • 21
  • 77
  • 125
Suule
  • 2,197
  • 4
  • 16
  • 42
  • 2
    I found this article, maybe this helps; http://www.java2s.com/Tutorials/Java/Java_io/1030__Java_nio_File_Owner_Permissions.htm – Casper Sep 20 '18 at 07:19
  • 1
    Try `Files.getFileAttributeView(path, AclFileAttributeView.class).getAcl()` which returns all `AclEntry`s and then use the [`principal()`](https://docs.oracle.com/javase/8/docs/api/java/nio/file/attribute/AclEntry.html#principal--) to test the user. – gthanop Sep 20 '18 at 07:44
  • Both of you were right, @thenopi57 answer work on windows. But Casper provide link with the solution. Thanks both. – Suule Sep 20 '18 at 08:03

1 Answers1

3

There is no implementation independent way to get this information.

You have to look at what platform you are executing on. e.g. on a typical UNIX file system there are owner, group and world permissions.

To check if user is owner of file is answered here: Get file/directory owner's name in Java As answers in above mentioned link tell, on some implementations getting file owner may fail.

A user may be disallowed to read/write a file as owner but still can perform operations based on group or world permissions. To check group you would have to query LDAP or UNIX groups or Active Directory depending upon filesystem and OS.

This becomes more complex when OS and filesystem support ACL along with regular UNIX permissions where fine grained per user permissions can be defined. Java has no standard API to access these. See "AclFileAttributeView aclAttr" always null on OpenSuSE Linux. The existing java.nio APIs won't always be helpful here.

Sticky bit also plays a role which in most UNIXes disallows non-owners of directory to move or delete files, but semantic vary, please read: https://en.wikipedia.org/wiki/Sticky_bit

TL;DR: There is not simple way and depending on your use case you would have to call your OS for getting per user file permissions.

Xolve
  • 22,298
  • 21
  • 77
  • 125