To *_*Kra 5 java linux filesystems
在Java中是否可以管理使用不同用户/组创建文件/目录(如果程序以ROOT运行)?
小智 5
可以实现JDK 7(Java NIO)
使用 setOwner() 方法......
public static Path setOwner(Path path,
UserPrincipal owner)
throws IOException
Run Code Online (Sandbox Code Playgroud)
用法示例: 假设我们想让“joe”成为文件的所有者:
Path path = ...
UserPrincipalLookupService lookupService =
provider(path).getUserPrincipalLookupService();
UserPrincipal joe = lookupService.lookupPrincipalByName("joe");
Files.setOwner(path, joe);
Run Code Online (Sandbox Code Playgroud)
从下面的网址获取更多相关信息
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());
}
}
Run Code Online (Sandbox Code Playgroud)
示例:获取所有者
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());
}
}
Run Code Online (Sandbox Code Playgroud)
您可以在 JDK 7 中使用新的 IO API ( Java NIO )来实现此目的
有 getOwner()/setOwner() 方法可用于管理文件的所有权,并且可以使用PosixFileAttributeView.setGroup()来管理组
以下代码片段展示了如何使用 setOwner 方法设置文件所有者:
Path file = ...;
UserPrincipal owner = file.GetFileSystem().getUserPrincipalLookupService()
.lookupPrincipalByName("sally");
Files.setOwner(file, owner);
Run Code Online (Sandbox Code Playgroud)
Files 类中没有用于设置组所有者的专用方法。但是,直接执行此操作的安全方法是通过 POSIX 文件属性视图,如下所示:
Path file = ...;
GroupPrincipal group =
file.getFileSystem().getUserPrincipalLookupService()
.lookupPrincipalByGroupName("green");
Files.getFileAttributeView(file, PosixFileAttributeView.class)
.setGroup(group);
Run Code Online (Sandbox Code Playgroud)