1

In Java, I would like to dynamically change the file permission of a Linux file. I have tried to set it with Files.setPosixFilePermissions as suggested from this other source: How do I programmatically change file permissions?, but I am getting the error

java.nio.file.FileSystemException: : Operation not permitted

I figured out that I am unable to set the file permissions as a user, since the file is owned by root. My question is: Is it possible to execute Files.setPosixFilePermissions by switching from user to root in java? And then switching back to user when done?

Here is the bulk of my code:

String path = "/usr/local/bin/driver"; try { Utility.setAsExecutable(path); } catch (IOException e) { logger.error("Unable to set driver as executable."); e.printStackTrace(); } public static void setAsExecutable(String filePath) throws IOException { // using PosixFilePermission to set file permissions 755 Set<PosixFilePermission> perms = new HashSet<PosixFilePermission>(); perms.add(PosixFilePermission.OWNER_READ); perms.add(PosixFilePermission.OWNER_WRITE); perms.add(PosixFilePermission.OWNER_EXECUTE); perms.add(PosixFilePermission.GROUP_READ); perms.add(PosixFilePermission.GROUP_EXECUTE); perms.add(PosixFilePermission.OTHERS_READ); perms.add(PosixFilePermission.OTHERS_EXECUTE); Files.setPosixFilePermissions(Paths.get(filePath), perms); logger.info("Modified as executable " + filePath); } 

1 Answer 1

2

There is no way to change the owner of a running process (be it a JVM or anything else).

You can however spawn a new, privileged process to do the "dirty" work.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.