윤현구
윤현구

Reputation: 487

In Java, how to set file owner to root?

I'm using MacOS and this is my sample code:

@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:

  1. I'm using IntelliJ, and I'm trying to run my JUnit test file.
  2. healthTcpConfRepository.findById(1L) returns true.
  3. myFilePath exists.

@Autowired
private HealthFileSystemServiceImpl healthFileSystemService;

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

Upvotes: 1

Views: 612

Answers (2)

Azeem
Azeem

Reputation: 14627

Please make sure that your IDE i.e. IntelliJ IDEA is running with root privileges while you execute your application.

If you're running it from a command line / terminal then it should also be executed with root.

Upvotes: 1

윤현구
윤현구

Reputation: 487

Thanks for @Azeem.

When i run as root with terminal, it is passed.

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

Upvotes: 0

Related Questions