I working with a web project that will be deployed with root, but the files created must be under another owner.
I have tried this:
String owner = "currentUser";
Path p = Files.createFile(Paths.get("myFile.log"));
if (owner != null && !owner.isEmpty()) {
UserPrincipalLookupService lookupService = FileSystems.getDefault().getUserPrincipalLookupService();
UserPrincipal userPrincipal = lookupService.lookupPrincipalByName(owner);
Files.setOwner(p, userPrincipal);
}
However, I encounter AccessDeniedException with setOwner() method.
java.nio.file.AccessDeniedException: myFile.log
at java.base/sun.nio.fs.WindowsException.translateToIOException(WindowsException.java:89)
at java.base/sun.nio.fs.WindowsException.rethrowAsIOException(WindowsException.java:103)
at java.base/sun.nio.fs.WindowsException.rethrowAsIOException(WindowsException.java:108)
at java.base/sun.nio.fs.WindowsAclFileAttributeView.setOwner(WindowsAclFileAttributeView.java:201)
at java.base/sun.nio.fs.FileOwnerAttributeViewImpl.setOwner(FileOwnerAttributeViewImpl.java:102)
at java.base/java.nio.file.Files.setOwner(Files.java:2163)
The OS is Window and this code is running with Tomcat and Intellij. The owner that I'm trying to set is the current user of my PC since I just want to test the function setOwner().
Do anyone have an idea why this exception is raised and how to fix it? Thank you in advance!