The PosixFileAttributes Interface
As the PosixFileAttributes interface is a subinterface of the BasicFileAttributes interface, a PosixFileAttributes object has both the basic set of file attributes and the POSIX-specific file attributes.
interface java.nio.file.attribute.PosixFileAttributes
extends BasicFileAttributes
UserPrincipal owner()
GroupPrincipal group()
Return the owner or the group of the directory entry, represented by the interface java.nio.file.attribute.UserPrincipal and its subinterface java.nio.file .attribute.GroupPrincipal, respectively.
Set<PosixFilePermission> permissions()
Returns a set with a copy of the POSIX permissions for the directory entry. Permissions are defined by the enum type PosixFilePermission discussed earlier in this chapter (Table 21.10, p. 1326).
The methods of the subinterface PosixFileAttributes augment the basic set of file attributes with the following POSIX-specific attributes: owner, group, and file permissions. The method printPosixFileAttributes() in the utility class FileUtils, shown below, prints the values of the POSIX-specific file attributes by calling the relevant methods on the PosixFileAttributes object that is passed as a parameter.
// Declared in the utility class FileUtils.
public static void printPosixFileAttributes(PosixFileAttributes pfa) {
out.println(“Printing POSIX-specific file attributes:”);
UserPrincipal user = pfa.owner();
GroupPrincipal group = pfa.group();
Set<PosixFilePermission> permissions = pfa.permissions();
String perms = PosixFilePermissions.toString(permissions);
out.println(“owner: ” + user);
out.println(“group: ” + group);
out.println(“permissions: ” + perms);
out.println();
}
The code below obtains a PosixFileAttributes object at (3) that pertains to the file denoted by the path reference. Both the printBasicFileAttributes() method and the printPosixFileAttributes() method are called at (4) and (5), respectively, with this PosixFileAttributes object as the parameter. The call to the printBasicFile-Attributes() method at (4) will print the basic file attributes in the PosixFile-Attributes object.
Path path = Path.of(“project”, “src”, “pkg”, “Main.java”);
out.println(“File: ” + path);
PosixFileAttributes pfa = Files.readAttributes(path, // (3)
PosixFileAttributes.class);
FileUtils.printBasicFileAttributes(pfa); // (4)
FileUtils.printPosixFileAttributes(pfa); // (5)
Possible output from the code:
File: project/src/pkg/Main.java
Printing basic file attributes:
…
Printing POSIX-specific file attributes:
owner: javadude
group: admin
permissions: rw-r–r–
Note that both the basic and the POSIX-specific file attributes in the PosixFileAttributes object are readonly, as the PosixFileAttributes interface does not provide any set methods. However, values of updatable file attributes can be changed by appropriate set methods of the Files class (p. 1321).
Leave a Reply