Java - Changing the Owner of a File Using the FileOwnerAttributeView


The following code demonstrates how to read and update the owner of a file using the FileOwnerAttributeView.


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 Main {
  public static void main(String[] args) throws IOException {
    try {//w  ww  . ja  va2  s .  c  om
      // Change the file path to an existing file on your machine
      Path path = Paths.get("C:\\myData\\");

      FileOwnerAttributeView foav = Files.getFileAttributeView(path,

      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();

      UserPrincipal newOwner = upls.lookupPrincipalByName("yourName");

      UserPrincipal changedOwner = foav.getOwner();
      System.out.format("New owner of %s is %s%n", path, changedOwner.getName());
    } catch (UnsupportedOperationException | IOException e) {


The following code uses the Files.setOwner() method to update the owner of a file identified with the path C:\myData\ on Windows:

UserPrincipal owner = get the owner;
Path path = Paths.get("C:\\myData\\");
Files.setOwner(path, owner);

Related Topic