Modifying the POSIX ownership of a file - Java File Path IO

Java examples for File Path IO:Unix File

Description

Modifying the POSIX ownership of a file

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.GroupPrincipal;
import java.nio.file.attribute.PosixFileAttributeView;
import java.nio.file.attribute.PosixFileAttributes;
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("home/docs/users.txt");
    try {/*from w ww .j ava  2s .c  o m*/
      PosixFileAttributeView view = Files.getFileAttributeView(path,
          PosixFileAttributeView.class);

      PosixFileAttributes attributes = view.readAttributes();

      System.out.println("Old Group: " + attributes.group().getName());
      System.out.println("Old Owner: " + attributes.owner().getName());
      System.out.println();

      UserPrincipalLookupService lookupService = FileSystems.getDefault()
          .getUserPrincipalLookupService();
      UserPrincipal userPrincipal = lookupService
          .lookupPrincipalByName("jennifer");
      GroupPrincipal groupPrincipal = lookupService
          .lookupPrincipalByGroupName("jennifer");
      view.setGroup(groupPrincipal);
      view.setOwner(userPrincipal);

      attributes = view.readAttributes();
      System.out.println("New Group: " + attributes.group().getName());
      System.out.println("New Owner: " + attributes.owner().getName());
      System.out.println();

    } catch (IOException ex) {
      ex.printStackTrace();
    }
  }
}

Related Tutorials