Preface
在 Linux/Unix 中你可以透過 chmod 命令來變更檔案的屬性, 在 JDK7 之後提供了類別 PosixFileAttributes 讓你讀取與設定檔案的屬性.
Sample Code
下面的範例代碼讓你從命令列參數輸入一個檔案的路徑, 程式會讀出該檔案的屬性並重置該檔案屬性為 0644:
- package john.nio.file.attribute;
- import java.nio.file.Files;
- import java.nio.file.Path;
- import java.nio.file.Paths;
- import java.nio.file.attribute.PosixFileAttributes;
- import java.nio.file.attribute.PosixFilePermission;
- import static java.nio.file.attribute.PosixFilePermission.*;
- import java.nio.file.attribute.PosixFilePermissions;
- import java.util.Set;
- public class PosixFileAttributesDemo {
- public static void main(String args[]) throws Exception
- {
- if(args.length==0)
- {
- System.out.printf("\t[Info] Usage: Arg1=File Path\n");
- return;
- }
- Path profile = Paths.get(args[0]);
- PosixFileAttributes attrs = Files.readAttributes(profile,
- PosixFileAttributes.class);
- Set
posixPermissions = attrs.permissions(); - String owner = attrs.owner().getName();
- String perms = PosixFilePermissions.toString(posixPermissions);
- System.out.printf("\t[Info] File=%s with permission: ", args[0]);
- System.out.format("%s %s%n", owner, perms);
- posixPermissions.clear();
- posixPermissions.add(OWNER_READ);
- posixPermissions.add(OWNER_WRITE);
- posixPermissions.add(GROUP_READ);
- posixPermissions.add(OTHERS_READ);
- System.out.printf("\t[Info] Reset permission to: %s\n", PosixFilePermissions.toString(posixPermissions));
- Files.setPosixFilePermissions(profile, posixPermissions);
- }
- }
Execution
假設你將上面代碼封裝到 Test.jar 中, 並設定 main-class 為 PosixFileAttributesDemo, 下面為執行過程:
Supplement
* Stackoverflow - How can I set the umask from within java?
* Linux Files and File Permission
沒有留言:
張貼留言