Close

Java IO & NIO - Files.setOwner() Examples

Java IO & NIO Java Java API 


Class:

java.nio.file.Files

java.lang.Objectjava.lang.Objectjava.nio.file.Filesjava.nio.file.FilesLogicBig

Method:

public static Path setOwner(Path path,
                            UserPrincipal owner)
                     throws IOException

Updates the file owner.

Parameters:
path - The path to the file
owner - The new file owner
Returns:
The path


Examples


package com.logicbig.example.files;

import java.io.IOException;
import java.nio.file.FileSystem;
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;

/**
* In windows, before running this example,
* you can change the owner of a file using following command
* (must run as admin).
* icacls "C:\temp\trish-file.txt" /setowner "trish" /T /C
* Given that current logged in user is "joe"
*/
public class SetOwnerExample {

public static void main(String... args) throws IOException {
Path path = Paths.get("C:\\temp\\trish-file.txt");
System.out.println("File: " + path);
System.out.println("Exists: " + Files.exists(path));
System.out.println("-- owner before --");
UserPrincipal owner = Files.getOwner(path);
System.out.println("Owner: " + owner);

System.out.println("-- lookup other user --");
FileSystem fileSystem = path.getFileSystem();
UserPrincipalLookupService service = fileSystem.getUserPrincipalLookupService();
UserPrincipal userPrincipal = service.lookupPrincipalByName("joe");
System.out.println("Found UserPrincipal: " + userPrincipal);

//changing owner
Files.setOwner(path, userPrincipal);

System.out.println("-- owner after --");
owner = Files.getOwner(path);
System.out.println("Owner: " + owner.getName());
}
}

Output

File: C:\temp\trish-file.txt
Exists: true
-- owner before --
Owner: JOEMCHN\trish (User)
-- lookup other user --
Found UserPrincipal: JOEMCHN\Joe (User)
-- owner after --
Owner: JOEMCHN\Joe




See Also