Java - File Input Output File Owner

Introduction

There are three ways to manage the owner of a file:

  • Files.getOwner()and Files.setOwner() methods.
  • Files.getAttribute() and Files.setAttribute() methods using "owner" as the attribute name.
  • FileOwnerAttributeView

UserPrincipal and GroupPrincipal interfaces manages the owner of a file.

UserPrincipal represents a user whereas a GroupPrincipal represents a group.

When you read the owner of a file, you get an instance of UserPrincipal.

getName() method on the UserPrincipal object gets the name of the user.

When you want to set the owner of a file, you need to get an object of the UserPrincipal from a user name in a string form.

To get a UserPrincipal from the file system, use UserPrincipalLookupService class returned from getUserPrincipalLookupService() method of the FileSystem class.

The following code gets a UserPrincipal object for a user whose user id is yourName:

Demo

import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.attribute.UserPrincipal;
import java.nio.file.attribute.UserPrincipalLookupService;

public class Main {
  public static void main(String[] args) throws Exception {
    FileSystem fs = FileSystems.getDefault();
    UserPrincipalLookupService upls = fs.getUserPrincipalLookupService();

    // Throws a UserPrincipalNotFoundException exception if the user yourName does not exist
    UserPrincipal user = upls.lookupPrincipalByName("yourName");
    System.out.format("User principal name is %s%n", user.getName());

  }//from w w  w  .  ja v  a 2 s .c  om
}

Result

You can use method chaining in the above code to avoid intermediate variables.

Demo

import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.attribute.UserPrincipal;

public class Main {
  public static void main(String[] args) throws Exception {
    FileSystem fs = FileSystems.getDefault();
    // UserPrincipalLookupService upls = fs.getUserPrincipalLookupService();
    UserPrincipal user = FileSystems.getDefault().getUserPrincipalLookupService().lookupPrincipalByName("yourName");
    System.out.format("User principal name is %s%n", user.getName());

  }//from   w w  w .  j a  v a 2s. c o m
}

Result

Related Topics