There are three ways to manage the owner of a file:
UserPrincipal and GroupPrincipal interfaces manages the owner of a file.
UserPrincipal represents a user whereas a GroupPrincipal represents a group.
When you read the owner of a file, you get an instance of UserPrincipal.
getName() method on the UserPrincipal object gets 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, use UserPrincipalLookupService class returned from getUserPrincipalLookupService() method of the FileSystem class.
The following code gets a UserPrincipal object for a user whose user id is yourName:
import java.nio.file.FileSystem; import java.nio.file.FileSystems; import java.nio.file.attribute.UserPrincipal; import java.nio.file.attribute.UserPrincipalLookupService; public class Main { public static void main(String[] args) throws Exception { FileSystem fs = FileSystems.getDefault(); UserPrincipalLookupService upls = fs.getUserPrincipalLookupService(); // Throws a UserPrincipalNotFoundException exception if the user yourName does not exist UserPrincipal user = upls.lookupPrincipalByName("yourName"); System.out.format("User principal name is %s%n", user.getName()); }//from w w w . ja v a 2 s .c om }
You can use method chaining in the above code to avoid intermediate variables.
import java.nio.file.FileSystem; import java.nio.file.FileSystems; import java.nio.file.attribute.UserPrincipal; public class Main { public static void main(String[] args) throws Exception { FileSystem fs = FileSystems.getDefault(); // UserPrincipalLookupService upls = fs.getUserPrincipalLookupService(); UserPrincipal user = FileSystems.getDefault().getUserPrincipalLookupService().lookupPrincipalByName("yourName"); System.out.format("User principal name is %s%n", user.getName()); }//from w w w . j a v a 2s. c o m }