在Java中是否可以管理使用不同用户/组创建文件/目录(如果程序以ROOT运行)?
答案 0 :(得分:4)
您可以实现JDK 7(Java NIO)
使用setOwner()方法....
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());
}
}
示例:GetOwner
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());
}
}
答案 1 :(得分:2)
您可以使用新的IO API(Java NIO)
在JDK 7中实现此目的有getOwner()/ setOwner()方法可用于管理文件的所有权,以及管理可以使用的组PosixFileAttributeView.setGroup()
以下代码段显示了如何使用setOwner方法设置文件所有者:
Path file = ...;
UserPrincipal owner = file.GetFileSystem().getUserPrincipalLookupService()
.lookupPrincipalByName("sally");
Files.setOwner(file, owner);
Files类中没有用于设置组所有者的特殊方法。但是,直接执行此操作的安全方法是通过POSIX文件属性视图,如下所示:
Path file = ...;
GroupPrincipal group =
file.getFileSystem().getUserPrincipalLookupService()
.lookupPrincipalByGroupName("green");
Files.getFileAttributeView(file, PosixFileAttributeView.class)
.setGroup(group);