The JSR 203 file attribute API
This tutorial is a guide to using the JSR 203 file attribute API.
This API appeared in Java 7 and, even today, it is seldomly used. It is however much more powerful than java.io.File.
The attribute API is located in
java.nio.file.attribute. You will use methods in
java.nio.file.Files to access them.
Views and attributes
There are two major components to the API: views and attributes. Some views provide attributes but others don't.
All views have a name; in the list below, it will be mentioned whether the given view has associated attributes:
All views inherit
FileAttributeView, which has a
name() method returning the name above.
Obtaining a file attribute view from a
In order to obtain a view from a path, you will use
Files.getFileAttributeView(). For instance, in order to obtain the
basic view from some path
path, you will use:
Obtaining file attributes from a
The method to use in this case is
Files.readAttributes(). Obtaining the
posix attributes from a path is done as such:
Getting the list of supported file attribute views
You can obtain a
Set<String> of all supported file attribute views by name using:
There are other methods which we will see below; in fact, there are several ways to obtain the same attribute from a
Path. For instance, if you have a file system implementing
acl, you have no less than twelve ways of obtaining the file owner!
Example: obtaining the size of a path
First way: using the
The easier way to obtain the size is to use this:
Second way: using file attributes
Here is another way:
Note that since
PosixFileAttributes both extend
BasicFileAttributes, it also means that you can substitute
BasicFileAttributes.class in the above with either, provided your filesystem supports it.
Third way: using
This method allows you to retrieve attributes by name; here you can use:
Note that it will return an
Object, you therefore need to cast. Also, if your filesystem supports
dos or both, you may also use
Fourth way: going through the view to read the attributes
You can also do this:
Similarly, you may also use
This was only a sample of the API; remind to get the list of supported file attribute views from the filesystem: not only those defined by the JDK exist!
For instance, if you open a
FileSystem to a zip file, you have a specific file attribute view with name
zip which you can use at your leisure.