java - 在 Windows XP SP2 中用 java (ver-7) 设置文件的所有者

标签 java

代码如下:

import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.Files;
import java.nio.file.attribute.UserPrincipalLookupService;
import java.nio.file.attribute.UserPrincipal;
import java.nio.file.FileSystems;
import java.lang.UnsupportedOperationException;
import java.io.IOException;

public class SetOwnerOfFile{
    public static void main(String args[]){
        Path path=Paths.get("c:\\demotext.txt");
        try{
            UserPrincipal owner=Files.getOwner(path);
            System.out.format("The owner of file is: %s%n",owner.getName());

            UserPrincipalLookupService lookupservice=FileSystems.getDefault().getUserPrincipalLookupService();
            Files.setOwner(path,lookupservice.lookupPrincipalByName("joe"));

            UserPrincipal newowner=Files.getOwner(path);
            System.out.format("Now the owner of file is: %s%n",newowner.getName());
        }
        catch(UnsupportedOperationException x){
            System.err.println(x);
        }
        catch(IOException x){
            System.err.println(x);
        }
    }
}

输出:
文件的所有者是:\Everyone
java.nio.file.attribute.UserPrincipalNotFoundException异常

程序抛出 IOException。这是否意味着我的操作系统限制修改文件的所有者?如果没有,请给我一些解决方案。

最佳答案

我验证了你的代码。 问题不在于更新 owner,而是找到 UserPrincinpal如果您拆分以下语句:

        UserPrincipalLookupService lookupservice=FileSystems.getDefault().getUserPrincipalLookupService();
        Files.setOwner(path,lookupservice.lookupPrincipalByName("joe"));

像这样:

        UserPrincipalLookupService lookupservice=FileSystems.getDefault().getUserPrincipalLookupService();
        UserPrincipal userPrincipal = lookupservice.lookupPrincipalByName("joe");
        Files.setOwner(path,userPrincipal);

您将在第二行遇到问题。可能是找不到名称为“joe”的现有“Windows 用户”

我对我的 Windows 用户进行了尝试,并成功更改了所有者。

关于java - 在 Windows XP SP2 中用 java (ver-7) 设置文件的所有者,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12731277/

相关文章:

java - 在构建Java RESTful Service时,什么有更大的优势——先为它们创建POJO还是XML文档?

java - 在元素重置之前找到它曾经是什么数字

java - Android java将两个相似的for循环合并为一个循环

java - 是否有解析转义字符的 Java 函数?

java - 在java中用 ""替换{?

java - 按 RecyclerView 的值升序/降序排序

java - org.dom4j.DocumentException : hibernate. 组织嵌套异常 : hibernate. 组织

java - 什么是对象引用变量?

java - 带有查询 Dsl 自定义绑定(bind)和/或操作的 Spring 不起作用

java - 函数参数优化的最终结果