Using the Files class' setOwner method - Java File Path IO

Java examples for File Path IO:File Owner

Description

Using the Files class' setOwner method

Demo Code

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.FileOwnerAttributeView;
import java.nio.file.attribute.UserPrincipal;
import java.nio.file.attribute.UserPrincipalLookupService;

public class Main {
  public static void main(String[] args) throws Exception {
    Path path = Paths.get("C:/home/docs/users.txt");
    try {//ww w . j a v  a2s  .  c  o m
      UserPrincipalLookupService lookupService = FileSystems.getDefault()
          .getUserPrincipalLookupService();

      UserPrincipal userPrincipal = lookupService
          .lookupPrincipalByName("jennifer");

      Files.setOwner(path, userPrincipal);
      
      FileOwnerAttributeView view = Files.getFileAttributeView(path,
          FileOwnerAttributeView.class);
      
      view.setOwner(userPrincipal);
      
      System.out.println("Owner: " + view.getOwner().getName());
    } catch (IOException ex) {
      ex.printStackTrace();
    }
  }
}

Related Tutorials