【问题标题】:In Java, how to set file owner to root?在Java中,如何将文件所有者设置为root?
【发布时间】:2020-01-30 08:27:10
【问题描述】:

我使用的是 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));
}

【问题讨论】:

  • 您的应用程序是以root 还是超级用户身份运行的?
  • @Azeem 是的。由超级用户
  • 您能否在您的问题中添加有关您如何运行它的步骤?从终端还是 IDE?
  • @Azeem 当然。我编辑我的问题。
  • 哇。这是无一例外的成功......我认为这是我的错误。感谢@Azeem

标签: java nio privileges elevated-privileges


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    感谢@Azeem。

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

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

    【讨论】:

      猜你喜欢
      • 2016-10-25
      • 2015-10-29
      • 2012-06-04
      • 2013-09-23
      • 2019-02-20
      • 1970-01-01
      • 1970-01-01
      • 2014-03-17
      • 1970-01-01
      相关资源
      最近更新 更多