Java PosixFileAttributeView remove one file permission

Introduction

The following table lists the PosixFilePermission enumeration values:

ValueLevel Permission Granted
GROUP_EXECUTEGroup Execute and search
GROUP_READGroup Read
GROUP_WRITE Group Write
OTHERS_EXECUTE Others Execute and search
OTHERS_READ OthersRead
OTHERS_WRITE Others Write
OWNER_EXECUTEOwner Execute and search
OWNER_READOwner Read
OWNER_WRITE Owner Write
import java.io.IOException;
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.security.Permissions;
import java.util.Set;

public class Main {

   public static void main(String[] args) {
      Path path = Paths.get("home/docs/users.txt");
      listPermissions(path);/*www  .j  av a  2  s.  co m*/
      setPermission(path, PosixFilePermission.OWNER_EXECUTE);
   }

   private static void setPermission(Path path, PosixFilePermission permission) {
      try {
         System.out.println("\nSetting permission for " + path.getFileName());
         PosixFileAttributeView view = Files.getFileAttributeView(path, PosixFileAttributeView.class);

         PosixFileAttributes attributes = view.readAttributes();

         Set<PosixFilePermission> permissions = attributes.permissions();
         permissions.remove(PosixFilePermission.OTHERS_WRITE); 
         permissions.add(permission);

         view.setPermissions(permissions);
         System.out.println();
      } catch (IOException ex) {
         ex.printStackTrace();
      }
   }

   private static void listPermissions(Path path) {
      try {
         System.out.println("Permission for " + path.getFileName());
         PosixFileAttributeView view = Files.getFileAttributeView(path, PosixFileAttributeView.class);
         PosixFileAttributes attributes = view.readAttributes();
         System.out.println("Group: " + attributes.group().getName());
         System.out.println("Owner: " + attributes.owner().getName());
         Set<PosixFilePermission> permissions = attributes.permissions();
         System.out.print("Permissions: ");
         for (PosixFilePermission permission : permissions) {
            System.out.print(permission.name() + " ");
         }
         System.out.println();
      } catch (IOException ex) {
         ex.printStackTrace();
      }
   }

}



PreviousNext

Related