In Java, I\'m dynamically creating a set of files and I\'d like to change the file permissions on these files on a linux/unix file system. I\'d like to be able to execute t
Full control over file attributes is available in Java 7, as part of the "new" New IO facility (NIO.2). For example, POSIX permissions can be set on an existing file with setPosixFilePermissions(), or atomically at file creation with methods like createFile() or newByteChannel().
You can create a set of permissions using EnumSet.of()
, but the helper method PosixFilePermissions.fromString() will uses a conventional format that will be more readable to many developers. For APIs that accept a FileAttribute
, you can wrap the set of permissions with with PosixFilePermissions.asFileAttribute().
Set ownerWritable = PosixFilePermissions.fromString("rw-r--r--");
FileAttribute> permissions = PosixFilePermissions.asFileAttribute(ownerWritable);
Files.createFile(path, permissions);
In earlier versions of Java, using native code of your own, or exec
-ing command-line utilities are common approaches.