代码如下:
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/