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

问题描述 投票:0回答:2

我正在使用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));
}
java nio privileges elevated-privileges
2个回答
0
投票
如果从命令行/终端运行它,那么它也应该用root执行。

0
投票
当我以root身份通过终端运行时,它通过。

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

© www.soinside.com 2019 - 2024. All rights reserved.