Java创建具有特定所有者(用户/组)的文件和目录



在Java中,是否可以管理与不同用户/组创建文件/目录(如果程序以ROOT运行)?

您可以实现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);

从以下url 获取有关相同内容的更多信息

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());
  }
}

您可以使用新的IO API(Java NIO)在JDK7中实现这一点

有getOwner()/setOwner(

以下代码片段显示了如何使用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);

最新更新