[英]In Java, how to set file owner to root?
I'm using MacOS and this is my sample code:我正在使用 MacOS,这是我的示例代码:
@Component
public class HealthFileSystemServiceImpl {
public HealthCommonConf saveYml(HealthCommonConf healthCommonConf) throws IOException {
Files.setOwner(Paths.get(myFilePath), FileSystems.getDefault().getUserPrincipalLookupService().lookupPrincipalByName("root"));
}
}
And I get this exception message:我收到此异常消息:
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)
How can I solve this?我该如何解决这个问题?
Edit编辑
Environment :环境:
healthTcpConfRepository.findById(1L)
returns true
. healthTcpConfRepository.findById(1L)
返回true
。myFilePath
exists. myFilePath
存在。@Autowired
private HealthFileSystemServiceImpl healthFileSystemService;
@Test
public void saveConf() throws IOException {
healthFileSystemService.saveYml(healthTcpConfRepository.findById(1L).orElse(null));
}
Please make sure that your IDE ie IntelliJ IDEA is running with root
privileges while you execute your application.请确保您的 IDE 即 IntelliJ IDEA 在您执行应用程序时以
root
权限运行。
If you're running it from a command line / terminal then it should also be executed with root
.如果您从命令行/终端运行它,那么它也应该使用
root
执行。
Thanks for @Azeem.感谢@Azeem。
When i run as root with terminal, it is passed.当我使用终端以 root 身份运行时,它通过了。
root# mvn clean test -Dtest={myPackage}.HealthFileSystemServiceImplTest#saveConf
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.