Search code examples
javaunixposix

How to set file owner/group when creating a file in Java


I would like to set a (unix) owner and group of a file created from Java. I would like something like this:

Path file = ...;
Set<PosixFilePermission> perms = PosixFilePermissions.fromString("rwxr-x---");
FileAttribute<Set<PosixFilePermission>> attr = PosixFilePermissions.asFileAttribute(perms);
Files.createFile(file, attr);

-- it is an example how to set permissions, but I cannot find how to do the same with owner/group.

Please note that I'm not interested in changing the owner after the file is created (this has already been answered on SO [1] [2]), but when the file is created.

Motivation for this question is that I need to make sure that the file I'm creating is not modified by other users while I set proper owner and permissions.


Solution

  • Setting ownership on file creation does not seem to be possible. When you look at the documentation of open() system call, it describes how to set file permissions, but the only mention of owner is:

    If the file does not exist it will be created. The owner (user ID) of the file is set to the effective user ID of the process. The group ownership (group ID) is set either to the effective group ID of the process or to the group ID of the parent directory

    See also this answer.

    The solution I went for in the end was this:

    1. Create the file with default owner but restrictive permissions 000:

      Path file = ...;
      Set<PosixFilePermission> perms = Collections.<PosixFilePermissions>emptySet();
      FileAttribute<Set<PosixFilePermission>> attr = PosixFilePermissions.asFileAttribute(perms);
      Files.createFile(file, attr);
      
    2. Change the owner/group to the target user

    3. The target user then sets permissions to what it needs.

    This should ensure that no other user can modify the file at any point in time.