Java Reference
In-Depth Information
// Read all basic attributes through the view
BasicFileAttributes bfa = bfv.readAttributes();
// Print some basic attributes
System.out.format("Size:%s bytes %n", bfa.size());
System.out.format("Creation Time:%s %n",
bfa.creationTime());
System.out.format("Last Access Time:%s %n",
bfa.lastAccessTime());
// Update the create time to the current time
FileTime newLastModifiedTime = null;
FileTime newLastAccessTime = null;
FileTime newCreateTime = FileTime.from(Instant.now());
// A null for time means youdo not want to update that time
bfv.setTimes(newLastModifiedTime,
newLastAccessTime,
newCreateTime);
}
catch (IOException e) {
e.printStackTrace();
}
}
}
Managing the Owner of a File
There are three ways to manage the owner of a file:
Files.getOwner() and Files.setOwner() methods.
Using
Files.getAttribute() and Files.setAttribute() methods using "owner" as the
attribute name.
Using
FileOwnerAttributeView .
You need to work with UserPrincipal and GroupPrincipal interfaces to manage the owner of a file.
The owner of a file could be a user or a group. A UserPrincipal represents a user whereas a GroupPrincipal
represents a group. When you read the owner of a file, you get an instance of UserPrincipal . Use the getName()
method on the UserPrincipal object to get the name of the user. When you want to set the owner of a file, you
need to get an object of the UserPrincipal from a user name in a string form. To get a UserPrincipal from the
file system, you need to use an instance of the UserPrincipalLookupService class, which you can get using
the getUserPrincipalLookupService() method of the FileSystem class. The following snippet of code gets a
UserPrincipal object for a user whose user id is ksharan :
Using the
FileSystem fs = FileSystems.getDefault();
UserPrincipalLookupService upls = fs.getUserPrincipalLookupService();
// Throws a UserPrincipalNotFoundException exception if the user ksharan does not exist
UserPrincipal user = upls.lookupPrincipalByName("ksharan");
System.out.format("User principal name is %s%n", user.getName());
 
Search WWH ::




Custom Search