java代码如何修改文件所有者呢?

重生 Java经验 发布时间:2023-12-23 17:39:52 阅读数:9205 1
下文笔者讲述使用Java代码修改文件所有者的方法及示例分享,如下所示

修改文件所有者的实现思路

我们可以Files中的静态方法
    setOwner修改文件的所有者
例:修改文件所有者的示例
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.UserPrincipal;
import java.nio.file.attribute.UserPrincipalLookupService;
import java.nio.file.attribute.FileOwnerAttributeView;
import java.io.IOException;
 
public class ChangeFileOwner {
    public static void main(String[] args) throws IOException {
        //获取文件路径
        Path filePath = Paths.get("/test/java265.txt");
        
        //查看文件所有者
        UserPrincipalLookupService lookupService = filePath.getFileSystem().getUserPrincipalLookupService();
        UserPrincipal owner = lookupService.lookupPrincipalByName("newowner");
        
        //修改文件所有者
        Files.getFileAttributeView(filePath, FileOwnerAttributeView.class).setOwner(owner);
    }
}
版权声明

本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。

本文链接: https://www.Java265.com/JavaJingYan/202312/17033244317553.html

最近发表

热门文章

好文推荐

Java265.com

https://www.java265.com

站长统计|粤ICP备14097017号-3

Powered By Java265.com信息维护小组

使用手机扫描二维码

关注我们看更多资讯

java爱好者