Java - Changing the Owner of a File Using the FileOwnerAttributeView

Introduction

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

Demo

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 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\\Main.java");

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

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

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

Result

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

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

Related Topic