繁体   English   中英

在 Java 中,如何将文件所有者设置为 root?

[英]In Java, how to set file owner to root?

我正在使用 MacOS,这是我的示例代码:

@Component
public class HealthFileSystemServiceImpl {
    public HealthCommonConf saveYml(HealthCommonConf healthCommonConf) throws IOException {
        Files.setOwner(Paths.get(myFilePath), FileSystems.getDefault().getUserPrincipalLookupService().lookupPrincipalByName("root"));
    }
}

我收到此异常消息:

java.nio.file.FileSystemException: /tmp/jmuser/healthService/monitor/Test-Jmsight-id_Test-Health-Name.yml: Operation not permitted

    at java.base/sun.nio.fs.UnixException.translateToIOException(UnixException.java:100)
    at java.base/sun.nio.fs.UnixException.rethrowAsIOException(UnixException.java:111)
    at java.base/sun.nio.fs.UnixException.rethrowAsIOException(UnixException.java:116)
    at java.base/sun.nio.fs.UnixFileAttributeViews$Posix.setOwners(UnixFileAttributeViews.java:268)
    at java.base/sun.nio.fs.UnixFileAttributeViews$Posix.setOwner(UnixFileAttributeViews.java:290)
    at java.base/sun.nio.fs.FileOwnerAttributeViewImpl.setOwner(FileOwnerAttributeViewImpl.java:100)
    at java.base/java.nio.file.Files.setOwner(Files.java:2163)

我该如何解决这个问题?


编辑

环境

  1. 我正在使用 IntelliJ,并且正在尝试运行我的 JUnit 测试文件。
  2. healthTcpConfRepository.findById(1L)返回true
  3. myFilePath存在。

@Autowired
private HealthFileSystemServiceImpl healthFileSystemService;

@Test
public void saveConf() throws IOException {
    healthFileSystemService.saveYml(healthTcpConfRepository.findById(1L).orElse(null));
}

请确保您的 IDE 即 IntelliJ IDEA 在您执行应用程序时以root权限运行。

如果您从命令行/终端运行它,那么它也应该使用root执行。

感谢@Azeem。

当我使用终端以 root 身份运行时,它通过了。

root# mvn clean test -Dtest={myPackage}.HealthFileSystemServiceImplTest#saveConf

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM