[英]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)
我该如何解决这个问题?
编辑
环境:
healthTcpConfRepository.findById(1L)
返回true
。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.