Java Reference
In-Depth Information
You can also read file attributes using a specific view object. You can use the
getFileAttributeView()
method
of the
Files
class to get a specific attribute view. It returns
null
if the file attribute view is not available. The method
declaration is as follows:
<V extends FileAttributeView> V getFileAttributeView(Path path, Class<V> type,
LinkOption... options)
•
Once you get a view object of a specific view type, you can read all attributes of that view type using the view
object's
readAttributes()
method. Note that not all views provide
readAttributes()
method. For example, the
FileOwnerAttributeView
provides only the
getOwner()
method to read the owner attribute of a file. If an attribute
view is updateable, the view object provides appropriate setter methods to update the attributes. The following
snippet of code reads all basic attributes for
C:\poems\luci1.txt
file using a basic view object:
// Get a Path object
Path path = Paths.get("C:\\poems\\luci1.txt");
// Get the basic view
BasicFileAttributeView bfv =
Files.getFileAttributeView(path, BasicFileAttributeView.class);
// Read all basic attributes through the view
BasicFileAttributes bfa = bfv.readAttributes();
The basic view lets you update the last modified time, the last accessed time, and the creation time of a file. The
setTimes()
method lets you update all three types of times. If you pass a
null
value for a time, it means you do not
want to update that time. The time you need to pass to the
setTimes()
method is of
FileTime
type.
Listing 10-15 demonstrates how to use the basic file attribute view to read and update basic file attributes.
Please change the file path in the
main()
method to the path of an existing file whose attributes you want to read.
The program uses a file path of
C:\poems\luci1.txt
on Windows that may not exist on your machine.
Listing 10-15.
Using Basic File Attribute View to Read and Update Basic File Attributes
// BasicFileAttributeViewTest.java
package com.jdojo.nio2;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.BasicFileAttributeView;
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.attribute.FileTime;
import java.time.Instant;
public class BasicFileAttributeViewTest {
public static void main(String[] args) {
// Change the path to point to your file
Path path = Paths.get("C:\\poems\\luci1.txt");
try {
// Get the basic view
BasicFileAttributeView bfv =
Files.getFileAttributeView(path,
BasicFileAttributeView.class);