文章详情

短信预约-IT技能 免费直播动态提醒

请输入下面的图形验证码

提交验证

短信预约提醒成功

java 如何为文件及文件夹添加权限

2024-04-02 19:55

关注

java 为文件及文件夹添加权限



public static void addChmod777(String filePath) throws IOException {
	if (!System.getProperty("os.name").startsWith("Win")) {
		String cmdGrant = "chmod 777 " + filePath;
		BaseLogMethod.logInfo(TAG, "File Augmentation after Moving:" + cmdGrant);
		Runtime.getRuntime().exec(cmdGrant);
	}
}

public static void addRChmod777(String filePath) throws IOException {
	if (!System.getProperty("os.name").startsWith("Win")) {
		String cmdGrant = "chmod -R 777 " + filePath;
		BaseLogMethod.logInfo(TAG, ".addRChmod777: File Augmentation after Moving:" + cmdGrant);
		Runtime.getRuntime().exec(cmdGrant);
	}
}

java 修改文件所有者及其权限

1.设置所有者

管理文件所有者

Files.getOwner()和Files.setOwner()方法

要使用UserPrincipal来管理文件的所有者

(1)更改文件的所有者


import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.FileOwnerAttributeView;
import java.nio.file.attribute.UserPrincipal;
import java.nio.file.attribute.UserPrincipalLookupService;
public class Main {
    public static void main(String[] args) {
        Path path = Paths.get("/www/test1.txt");
        FileOwnerAttributeView foav = Files.getFileAttributeView(path,
                FileOwnerAttributeView.class);
        try {
            UserPrincipal owner = foav.getOwner();
            System.out.format("Original owner  of  %s  is %s%n", path,
                    owner.getName());
            FileSystem fs = FileSystems.getDefault();
            UserPrincipalLookupService upls = fs.getUserPrincipalLookupService();
            UserPrincipal newOwner = upls.lookupPrincipalByName("abc");
            foav.setOwner(newOwner);
            UserPrincipal changedOwner = foav.getOwner();
            System.out.format("New owner  of  %s  is %s%n", path,
                    changedOwner.getName());
        }catch (IOException e){
            e.printStackTrace();
        }
    }
}

输出

查看文件详细信息

2.ACL文件权限

Windows上支持ACL类型文件属性

使用AclFileAttributeView的

(1)读取文件e:/test1.txt的ACL条目


import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.AclEntry;
import java.nio.file.attribute.AclEntryPermission;
import java.nio.file.attribute.AclFileAttributeView;
import java.util.List;
import java.util.Set;
public class Main {
    public static void main(String[] args) {       
        Path path = Paths.get("e:/test1.txt");
        AclFileAttributeView aclView = Files.getFileAttributeView(path,
                AclFileAttributeView.class);
        if (aclView == null) {
            System.out.format("ACL view  is not  supported.%n");
            return;
        }
        try {
            List<AclEntry> aclEntries = aclView.getAcl();
            for (AclEntry entry : aclEntries) {
                System.out.format("Principal: %s%n", entry.principal());
                System.out.format("Type: %s%n", entry.type());
                System.out.format("Permissions are:%n");
                Set<AclEntryPermission> permissions = entry.permissions();
                for (AclEntryPermission p : permissions) {
                    System.out.format("%s %n", p);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

输出结果为

Principal: BUILTIN\Administrators (Alias)
Type: ALLOW
Permissions are:
WRITE_DATA
WRITE_OWNER
APPEND_DATA
SYNCHRONIZE
WRITE_ATTRIBUTES
EXECUTE
READ_DATA
DELETE_CHILD
READ_ATTRIBUTES
WRITE_NAMED_ATTRS
WRITE_ACL
DELETE
READ_ACL
READ_NAMED_ATTRS
Principal: NT AUTHORITY\SYSTEM (Well-known group)
Type: ALLOW
Permissions are:
WRITE_DATA
WRITE_OWNER
APPEND_DATA
SYNCHRONIZE
WRITE_ATTRIBUTES
EXECUTE
READ_DATA
DELETE_CHILD
READ_ATTRIBUTES
WRITE_NAMED_ATTRS
WRITE_ACL
DELETE
READ_ACL
READ_NAMED_ATTRS
Principal: NT AUTHORITY\Authenticated Users (Well-known group)
Type: ALLOW
Permissions are:
WRITE_DATA
READ_ATTRIBUTES
APPEND_DATA
WRITE_NAMED_ATTRS
SYNCHRONIZE
WRITE_ATTRIBUTES
EXECUTE
DELETE
READ_DATA
READ_ACL
READ_NAMED_ATTRS
Principal: BUILTIN\Users (Alias)
Type: ALLOW
Permissions are:
READ_ATTRIBUTES
SYNCHRONIZE
EXECUTE
READ_DATA
READ_ACL
READ_NAMED_ATTRS

(2)为指定用户添加新的ACL条目

e:/test1.txt为用户abc添加DATA_READ和DATA_ WRITE权限


import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.*;
import java.util.EnumSet;
import java.util.List;
import java.util.Set;
import static java.nio.file.attribute.AclEntryPermission.READ_DATA;
import static java.nio.file.attribute.AclEntryPermission.WRITE_DATA;
public class Main {
    public static void main(String[] args) {
        
        Path path = Paths.get("e:/test1.txt");
        AclFileAttributeView aclView = Files.getFileAttributeView(path,
                AclFileAttributeView.class);
        if (aclView == null) {
            System.out.format("ACL view  is not  supported.%n");
            return;
        }
        try {
            UserPrincipal bRiceUser = FileSystems.getDefault()
                    .getUserPrincipalLookupService().lookupPrincipalByName("abc");
            Set<AclEntryPermission> permissions = EnumSet.of(READ_DATA, WRITE_DATA);
            AclEntry.Builder builder = AclEntry.newBuilder();
            builder.setPrincipal(bRiceUser);
            builder.setType(AclEntryType.ALLOW);
            builder.setPermissions(permissions);
            AclEntry newEntry = builder.build();
            List<AclEntry> aclEntries = aclView.getAcl();
            aclEntries.add(newEntry);
            aclView.setAcl(aclEntries);
        }catch (IOException e){
            e.printStackTrace();
        }
    }
}

输出结果比刚才多了

Principal: hkgi-PC\abc (User)
Type: ALLOW
Permissions are:
WRITE_DATA
READ_DATA

3.POSIX文件权限

UNIX支持POSIX标准文件属性

PosixFilePermission枚举类型定义九个常量,每个权限组件一个。

九个常数命名为X_Y,其中X是OWNER,GROUP和OTHERS,Y是READ,WRITE和EXECUTE。

(1)输出/www/test1.txt的权限


import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.*;
import java.util.Set;
public class Main {
    public static void main(String[] args) {
        Path path = Paths.get("/www/test1.txt");
        PosixFileAttributeView posixView = Files.getFileAttributeView(path,
                PosixFileAttributeView.class);
        try{
            PosixFileAttributes attribs = posixView.readAttributes();
            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);
        }catch (IOException e){
            e.printStackTrace();
        }
    }
}

输出结果

rw-r--r--

(2)读取和更新名为test的文件权限


import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.*;
import java.util.EnumSet;
import java.util.Set;
import static java.nio.file.attribute.PosixFilePermission.*;
public class Main {
    public static void main(String[] args) {
        Path path = Paths.get("/www/test1.txt");
        PosixFileAttributeView posixView = Files.getFileAttributeView(path,
                PosixFileAttributeView.class);
        if (posixView == null) {
            System.out.format("POSIX attribute view  is not  supported%n.");
            return;
        }
        System.out.println("old:");
        readPermissions(posixView);
        updatePermissions(posixView);
        System.out.println("new:");
        readPermissions(posixView);
    }
    public static void readPermissions(PosixFileAttributeView posixView) {
        try{
            PosixFileAttributes attribs;
            attribs = posixView.readAttributes();
            Set<PosixFilePermission> permissions = attribs.permissions();
            // Convert the set of posix file permissions into rwxrwxrwx form
            String rwxFormPermissions = PosixFilePermissions.toString(permissions);
            System.out.println(rwxFormPermissions);
        }catch (IOException e){
            e.printStackTrace();
        }
    }
    public static void updatePermissions(PosixFileAttributeView posixView) {
        try {
            Set<PosixFilePermission> permissions = EnumSet.of(OWNER_READ, OWNER_WRITE,OWNER_EXECUTE,
                    GROUP_READ,GROUP_WRITE);
            posixView.setPermissions(permissions);
            System.out.println("Permissions set successfully.");
        }catch (IOException e){
            e.printStackTrace();
        }
    }
}

输出结果

old:
rw-r-----
Permissions set successfully.
new:
rwxrw----

以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程网。

阅读原文内容投诉

免责声明:

① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。

② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341

软考中级精品资料免费领

  • 历年真题答案解析
  • 备考技巧名师总结
  • 高频考点精准押题
  • 2024年上半年信息系统项目管理师第二批次真题及答案解析(完整版)

    难度     807人已做
    查看
  • 【考后总结】2024年5月26日信息系统项目管理师第2批次考情分析

    难度     351人已做
    查看
  • 【考后总结】2024年5月25日信息系统项目管理师第1批次考情分析

    难度     314人已做
    查看
  • 2024年上半年软考高项第一、二批次真题考点汇总(完整版)

    难度     433人已做
    查看
  • 2024年上半年系统架构设计师考试综合知识真题

    难度     221人已做
    查看

相关文章

发现更多好内容

猜你喜欢

AI推送时光机
位置:首页-资讯-后端开发
咦!没有更多了?去看看其它编程学习网 内容吧
首页课程
资料下载
问答资讯