Java PosixFileAttributeView get file permission in rwxrwxrwx form

Description

Java PosixFileAttributeView get file permission in rwxrwxrwx form

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 = posixView.readAttributes();
    System.out.println(attribs.isSymbolicLink());

    // 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);
  }/* w  ww .  j a va2s .com*/
}



PreviousNext

Related