Example of UserPrincipal in Java NIO

By Arvind Rai, December 12, 2013
java.nio.file.attribute.UserPrincipal has been introduced in JDK 7. UserPrincipal represents user rights for any file in file system. A file can have an owner and UserPrincipal represents that attributes related to the user ownership. UserPrincipal can be initiated by UserPrincipalLookupService and FileAttributeView. Here in our example we are using UserPrincipalLookupService to initialize UserPrincipal.

UserPrincipalLookupService in Java NIO

java.nio.file.attribute.UserPrincipalLookupService is the part of JDK 7 and is an NIO API. To get UserPrincipal , UserPrincipalLookupService provides the methods that is based by name or by group name. These methods are

lookupPrincipalByGroupName() : It accepts account name and returns GroupPrincipal. It is used to look up groups of users.
lookupPrincipalByName() : It accepts user name and returns UserPrincipal. It is used to look up user. In our example we will use lookupPrincipalByName().

Files.setOwner() in Java NIO

setOwner() is the method of java.nio.file.Files. This method sets and updates the owner of a file. It accepts the Path and UserPrincipal as owner.

Files.getOwner() in Java NIO

getOwner() is the method of java.nio.file.Files. We pass the file path and it returns UserPrincipal. In this way with the help of getOwner(), we can get the information of a file.
package com.concretepage.io.file.attribute;
import java.io.IOException;
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.UserPrincipal;
import java.nio.file.attribute.UserPrincipalLookupService;
public class UserPrincipalExample {
	public static void main(String[] args) throws IOException {
		Path file = Paths.get("D:/cp","UserPrincipalLookupServiceExample.java");
		UserPrincipalLookupService lookupService = FileSystems.getDefault().getUserPrincipalLookupService();
		UserPrincipal owner = lookupService.lookupPrincipalByName("arai"); 
		Files.setOwner(file, owner);
	    UserPrincipal userPrincipal =  Files.getOwner(file);
In the example arai is a user. The owner ship of the file has been set for user arai.

©2024 concretepage.com | Privacy Policy | Contact Us