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

7

如果程序以ROOT身份运行,Java是否可以管理创建具有不同用户/组的文件/目录?


1
类似于这样?https://dev59.com/W2Yr5IYBdhLWcg3w--6U - pL4Gu33
2个回答

5
您可以使用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());

  }
}

示例:获取所有者

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

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接