• java 7修改文件权限


    Full control over file attributes is available in Java 7, as part of the "new" New IO facility (NIO.2). For example, POSIX permissions can be set with setPosixFilePermissions().

    import java.io.File;
    import java.io.IOException;
    import java.nio.file.Files;
    import java.nio.file.Paths;
    import java.nio.file.attribute.PosixFilePermission;
    import java.util.HashSet;
    import java.util.Set;
    
    public class FilePermissions {
    
        /**
         * File Permissions Java Example using File and PosixFilePermission
         * @param args
         * @throws IOException 
         */
        public static void main(String[] args) throws IOException {
            File file = new File("/Users/pankaj/temp.txt");
            
            //set application user permissions to 455
            file.setExecutable(false);
            file.setReadable(false);
            file.setWritable(true);
            
            //change permission to 777 for all the users
            //no option for group and others
            file.setExecutable(true, false);
            file.setReadable(true, false);
            file.setWritable(true, false);
            
            //using PosixFilePermission to set file permissions 777
            Set<PosixFilePermission> perms = new HashSet<PosixFilePermission>();
            //add owners permission
            perms.add(PosixFilePermission.OWNER_READ);
            perms.add(PosixFilePermission.OWNER_WRITE);
            perms.add(PosixFilePermission.OWNER_EXECUTE);
            //add group permissions
            perms.add(PosixFilePermission.GROUP_READ);
            perms.add(PosixFilePermission.GROUP_WRITE);
            perms.add(PosixFilePermission.GROUP_EXECUTE);
            //add others permissions
            perms.add(PosixFilePermission.OTHERS_READ);
            perms.add(PosixFilePermission.OTHERS_WRITE);
            perms.add(PosixFilePermission.OTHERS_EXECUTE);
            
            Files.setPosixFilePermissions(Paths.get("/Users/pankaj/run.sh"), perms);
        }
    
    }
    

    From above example, it’s clear that PosixFilePermission provides more options and code is more readable. If you are using Java 7, you should use it for setting file permissions in java.

  • 相关阅读:
    (转)SpringMVC学习总结
    Golang-函数的defer
    Golang-闭包
    Golang-匿名函数
    Golang-init()
    Golang-递归
    Golang-函数、包、变量的作用域
    Golang-for、break、continue、goto、return
    Golang-程序流程控制 if、switch
    Golang-进制、源码反码补码、位运算
  • 原文地址:https://www.cnblogs.com/hupengcool/p/4065206.html
Copyright © 2020-2023  润新知