Managing Attributes and Permissions Files and Directories - Java File Path IO

Java examples for File Path IO:Directory

Description

Managing Attributes and Permissions Files and Directories

Demo Code

import java.io.IOException;
import java.nio.file.FileSystem;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.FileAttribute;
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("home/docs/users.txt");
    try {/*from w w w  .  j a va  2 s .  co m*/
      PosixFileAttributeView view = Files.getFileAttributeView(path,
          PosixFileAttributeView.class);

      PosixFileAttributes attributes = view.readAttributes();
      Set<PosixFilePermission> permissions = attributes.permissions();

      for (PosixFilePermission permission : permissions) {
        System.out.print(permission.toString() + ' ');
      }
      System.out.println();

      FileAttribute<Set<PosixFilePermission>> fileAttributes = PosixFilePermissions
          .asFileAttribute(permissions);
      Set<PosixFilePermission> fileAttributeSet = fileAttributes.value();
      for (PosixFilePermission posixFilePermission : fileAttributeSet) {
        System.out.print(posixFilePermission.toString() + ' ');
      }

      System.out.println();
      System.out.println(PosixFilePermissions.toString(permissions));
      permissions = PosixFilePermissions.fromString("rw-rw-r--");
      for (PosixFilePermission permission : permissions) {
        System.out.print(permission.toString() + ' ');
      }
      System.out.println();

    } catch (IOException ex) {
    }
  }
}

Related Tutorials