The BasicFileAttributes Interface – Java I/O: Part II

The BasicFileAttributes Interface

The methods of the java.nio.file.attribute.BasicFileAttributes interface reflect the basic set of file attributes that are common to most file systems.

Click here to view code image

interface java.nio.file.attribute.BasicFileAttributes
long size()

Returns the size of the directory entry (in bytes).

boolean isDirectory()
boolean isRegularFile()
boolean isSymbolicLink()
boolean isOther()

Determine whether the directory entry is of a specific kind.

Click here to view code image

FileTime lastModifiedTime()
FileTime lastAccessTime()
FileTime creationTime()

Return the appropriate timestamp for the directory entry.

The method printBasicFileAttributes() of the utility class FileUtils, shown below, prints the values of the basic file attributes by calling the relevant methods on the BasicFileAttributes object that is passed as a parameter.

Click here to view code image

// Declared in utility class FileUtils.
public static void printBasicFileAttributes(BasicFileAttributes bfa) {
  out.println(“Printing basic file attributes:”);
  out.println(“lastModifiedTime: ” + bfa.lastModifiedTime());
  out.println(“lastAccessTime:   ” + bfa.lastAccessTime());
  out.println(“creationTime:     ” + bfa.creationTime());
  out.println(“size:             ” + bfa.size());
  out.println(“isDirectory:      ” + bfa.isDirectory());
  out.println(“isRegularFile:    ” + bfa.isRegularFile());
  out.println(“isSymbolicLink:   ” + bfa.isSymbolicLink());
  out.println(“isOther:          ” + bfa.isOther());
  out.println();
}

The code below obtains a BasicFileAttributes object at (1) that pertains to the file denoted by the path reference. The printBasicFileAttributes() method is called at (2) with this BasicFileAttributes object as the parameter.

Click here to view code image

Path path = Path.of(“project”, “src”, “pkg”, “Main.java”);
out.println(“File: ” + path);
BasicFileAttributes bfa = Files.readAttributes(path,                   // (1)
                                               BasicFileAttributes.class);
FileUtils.printBasicFileAttributes(bfa);                               // (2)

Possible output from the code:

Click here to view code image

File: project/src/pkg/Main.java
Printing basic file attributes:
lastModifiedTime: 2021-07-23T10:15:34.854Z
lastAccessTime:   2021-07-23T10:16:33.166281Z
creationTime:     2021-07-20T23:03:58Z
size:             116
isDirectory:      false
isRegularFile:    true
isSymbolicLink:   false
isOther:          false

Note that the basic file attributes in the BasicFileAttributes object are read-only, as the BasicFileAttributes 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).

Categories: , ,

Leave a Reply

Your email address will not be published. Required fields are marked *