Java FileSystem change file owner

Description

Java FileSystem change file owner

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) {
    try {//from w  w  w .j a v a 2s. c om
      Path path = Paths.get("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("abc");
      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();
    }
  }
}



PreviousNext

Related