How do I programmatically change file permissions?

前端 未结 12 1235
深忆病人
深忆病人 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:45

    Prior to Java 6, there is no support of file permission update at Java level. You have to implement your own native method or call Runtime.exec() to execute OS level command such as chmod.

    Starting from Java 6, you can useFile.setReadable()/File.setWritable()/File.setExecutable() to set file permissions. But it doesn't simulate the POSIX file system which allows to set permission for different users. File.setXXX() only allows to set permission for owner and everyone else.

    Starting from Java 7, POSIX file permission is introduced. You can set file permissions like what you have done on *nix systems. The syntax is :

    File file = new File("file4.txt");
    file.createNewFile();
    
    Set perms = new HashSet<>();
    perms.add(PosixFilePermission.OWNER_READ);
    perms.add(PosixFilePermission.OWNER_WRITE);
    
    Files.setPosixFilePermissions(file.toPath(), perms);
    

    This method can only be used on POSIX file system, this means you cannot call it on Windows system.

    For details on file permission management, recommend you to read this post.

提交回复
热议问题