Java Reference
In-Depth Information
// Add the ACL entry for brice to the existing list
aclEntries.add(newEntry);
// Update the ACL entries
aclView.setAcl(aclEntries);
System.out.println("ACL entry added for brice successfully");
}
catch (IOException e) {
e.printStackTrace();
}
}
}
Managing POSIX File Permissions
In this section, I will cover managing file permissions using
PosixFileAttributeView
. Note that UNIX supports
POSIX standard file attributes. POSIX file permissions consist of nine components: three for the owner, three for
the group, and three for others. The three types of permissions are read, write, and execute. A typical POSIX file
permission in a string form looks like
"rw-rw----"
, which has read and write permissions for the owner and the
group. The
PosixFilePermission
enum type defines nine constants, one for each permission component. The nine
constants are named as
XXX_YYY
, where
XXX
is
OWNER
,
GROUP
, and
OTHERS
, and
YYY
is
READ
,
WRITE
, and
EXECUTE
.
PosixFilePermissions
is a utility class that has methods to convert the POSIX permissions of a file from one
form to another. Its
toString()
method converts a
Set
of
PosixFilePermission
enum constants into a string of the
rwxrwxrwx
form. Its
fromString()
method converts the POSIX file permissions in a string of the
rwxrwxrwx
form to a
Set
of
PosixFilePermission
enum constants. Its
asFileAttribute()
method converts a
Set
of
PosixFilePermission
enum constants into a
FileAttribute
object, which you can use in the
Files.createFile()
method as an argument
when creating a new file.
Reading POSIX file permissions is easy. You need to use the
readAttributes()
method of the
PosixFileAttributeView
class to get an instance of
PosixFileAttributes
. The
permissions()
method of
PosixFileAttributes
returns all POSIX file permissions as a
Set
of
PosixFilePermission
enum constants. The
following snippet of code reads and prints POSIX file permissions in the
rwxrwxrwx
form for a file named
luci
in the
default directory:
// Get a Path object for lici file
Path path = Paths.get("luci");
// Get the POSIX attribute view for the file
PosixFileAttributeView posixView =
Files.getFileAttributeView(path, PosixFileAttributeView.class);
// Here, make sure posixView is not null
// Read all POSIX attributes
PosixFileAttributes attribs; attribs = posixView.readAttributes();
// Read the file permissions
Set<PosixFilePermission> permissions = attribs.permissions();
// Convert the file permissions into the rwxrwxrwx string form
String rwxFormPermissions = PosixFilePermissions.toString(permissions);