How do I programmatically change file permissions?

前端 未结 12 1048
深忆病人
深忆病人 2020-11-22 04:55

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

12条回答
  •  [愿得一人]
    2020-11-22 05:39

    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.

提交回复
热议问题