Java - POSIX File Permissions

Introduction

UNIX supports POSIX standard file attributes.

POSIX file permissions consist of nine components: three for the owner, three for the group, and three for others.

The three types of permissions are read, write, and execute.

A typical POSIX file permission in a string form looks like "rw-rw----", which has read and write permissions for the owner and the group.

The PosixFilePermission enum type defines nine constants, one for each permission component.

The nine constants are named as XXX_YYY, where XXX is OWNER, GROUP, and OTHERS, and YYY is READ, WRITE, and EXECUTE.

PosixFilePermissions class converts the POSIX permissions of a file from one form to another.

Its toString() method converts a Set of PosixFilePermission enum constants into a string of the rwxrwxrwx form.

Its fromString() method converts the POSIX file permissions in a string of the rwxrwxrwx form to a Set of PosixFilePermission enum constants.

To read POSIX file permissions, use the readAttributes() method of the PosixFileAttributeView class to get an instance of PosixFileAttributes.

permissions() method of PosixFileAttributes returns all POSIX file permissions as a Set of PosixFilePermission enum constants.

The following code reads and prints POSIX file permissions in the rwxrwxrwx form for a file.

Demo

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.PosixFileAttributeView;
import java.nio.file.attribute.PosixFileAttributes;
import java.nio.file.attribute.PosixFilePermission;
import java.nio.file.attribute.PosixFilePermissions;
import java.util.Set;

public class Main {
  public static void main(String[] args) throws Exception {

    Path path = Paths.get("test");

    // Get the POSIX attribute view for the file
    PosixFileAttributeView posixView = Files.getFileAttributeView(path, PosixFileAttributeView.class);

    // Here, make sure posixView is not null

    // Read all POSIX attributes
    PosixFileAttributes attribs;/*from w  w  w  .  ja v  a 2 s.co  m*/
    attribs = posixView.readAttributes();

    // Read the file permissions
    Set<PosixFilePermission> permissions = attribs.permissions();

    // Convert the file permissions into the rwxrwxrwx string form
    String rwxFormPermissions = PosixFilePermissions.toString(permissions);

    // Print the permissions
    System.out.println(rwxFormPermissions);
  }
}

Result

Related Topics