Java Reference
In-Depth Information
You can use method chaining in the above snippet of code to avoid intermediate variables.
UserPrincipal user = FileSystems.getDefault()
.getUserPrincipalLookupService()
.lookupPrincipalByName("ksharan");
System.out.format("User principal name is %s%n", user.getName());
The user principal lookup service is an optional operation for a file system. You need to handle the
UnsupportedOperationException
that is thrown when the file system does not support it.
To get a
GroupPrincipal
instance, use the
lookupPrincipalByGroupName()
method of the user principal lookup
service. Once you get a
UserPrincipal
or
GroupPrincipal
instance that represents the owner of the file, you can use
any of the three methods described in the beginning of this section to update the owner of a file.
Listing 10-16 demonstrates how to read and update the owner of a file using the
FileOwnerAttributeView
.
Please change the file path in the
main()
method to an existing file on your machine before you run the program.
The program uses
brice
as the new user for the file. Please change the new user id to a user that exists on your machine.
If the user does not exist on your machine, you may get a
UserPrincipalNotFoundException
exception. You may get a
different output when you run the program.
Listing 10-16.
Changing the Owner of a File Using the FileOwnerAttributeView
// FileOwnerManagement.java
package com.jdojo.nio2;
import java.io.IOException;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.FileOwnerAttributeView;
import java.nio.file.attribute.UserPrincipal;
import java.nio.file.attribute.UserPrincipalLookupService;
public class FileOwnerManagement {
public static void main(String[] args) throws IOException {
try {
// Change the file path to an existing file on your machine
Path path = Paths.get("C:\\poems\\luci1.txt");
FileOwnerAttributeView foav =
Files.getFileAttributeView(
path,FileOwnerAttributeView.class);
UserPrincipal owner = foav.getOwner();
System.out.format("Original owner of %s is %s%n",
path, owner.getName());
FileSystem fs = FileSystems.getDefault();
UserPrincipalLookupService upls =
fs.getUserPrincipalLookupService();