如果程序以ROOT身份运行,Java是否可以管理创建具有不同用户/组的文件/目录?
如果程序以ROOT身份运行,Java是否可以管理创建具有不同用户/组的文件/目录?
public static Path setOwner(Path path,
UserPrincipal owner)
throws IOException
使用示例: 假设我们想将文件的所有者更改为 "joe":
Path path = ...
UserPrincipalLookupService lookupService =
provider(path).getUserPrincipalLookupService();
UserPrincipal joe = lookupService.lookupPrincipalByName("joe");
Files.setOwner(path, joe);
以下网址中可以获得关于同一内容的更多信息:
http://docs.oracle.com/javase/tutorial/essential/io/file.html
示例:设置所有者
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.FileOwnerAttributeView;
import java.nio.file.attribute.UserPrincipal;
import java.nio.file.attribute.UserPrincipalLookupService;
public class Test {
public static void main(String[] args) throws Exception {
Path path = Paths.get("C:/home/docs/users.txt");
FileOwnerAttributeView view = Files.getFileAttributeView(path,
FileOwnerAttributeView.class);
UserPrincipalLookupService lookupService = FileSystems.getDefault()
.getUserPrincipalLookupService();
UserPrincipal userPrincipal = lookupService.lookupPrincipalByName("mary");
Files.setOwner(path, userPrincipal);
System.out.println("Owner: " + view.getOwner().getName());
}
}
示例:获取所有者
(涉及IT技术相关内容)import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.FileOwnerAttributeView;
import java.nio.file.attribute.UserPrincipal;
public class Test {
public static void main(String[] args) throws Exception {
Path path = Paths.get("C:/home/docs/users.txt");
FileOwnerAttributeView view = Files.getFileAttributeView(path,
FileOwnerAttributeView.class);
UserPrincipal userPrincipal = view.getOwner();
System.out.println(userPrincipal.getName());
}
}
Path file = ...;
UserPrincipal owner = file.GetFileSystem().getUserPrincipalLookupService()
.lookupPrincipalByName("sally");
Files.setOwner(file, owner);
Path file = ...;
GroupPrincipal group =
file.getFileSystem().getUserPrincipalLookupService()
.lookupPrincipalByGroupName("green");
Files.getFileAttributeView(file, PosixFileAttributeView.class)
.setGroup(group);