Javaでファイル許可を設定する方法
Javaでは、ファイル許可は非常にOS固有です:* nix、NTFS(windows)およびFAT / FAT32は、すべて異なる種類のファイル許可を持っています。 Javaには、それに対処するための一般的なファイル許可がいくつか付属しています。
Check if the file permission allow:
-
file.canExecute(); – return true, file is executable; false is not.
-
file.canWrite(); – return true, file is writable; false is not.
-
file.canRead(); – return true, file is readable; false is not.
Set the file permission:
-
file.setExecutable(boolean); – true, allow execute operations; false to disallow it.
-
file.setReadable(boolean); – true, allow read operations; false to disallow it.
-
file.setWritable(boolean); – true, allow write operations; false to disallow it.
* nixシステムでは、ファイルのアクセス許可に関する詳細を設定する必要がある場合があります。たとえば、ファイルまたはディレクトリに777のアクセス許可を設定しますが、Java IOクラスにはそのための準備ができていないメソッドがありますが、次の汚い回避策を使用できます:
Runtime.getRuntime().exec("chmod 777 file");
ファイル許可の例
package com.example.file;
import java.io.File;
import java.io.IOException;
public class FilePermissionExample
{
public static void main( String[] args )
{
try {
File file = new File("/example/shellscript.sh");
if(file.exists()){
System.out.println("Is Execute allow : " + file.canExecute());
System.out.println("Is Write allow : " + file.canWrite());
System.out.println("Is Read allow : " + file.canRead());
}
file.setExecutable(false);
file.setReadable(false);
file.setWritable(false);
System.out.println("Is Execute allow : " + file.canExecute());
System.out.println("Is Write allow : " + file.canWrite());
System.out.println("Is Read allow : " + file.canRead());
if (file.createNewFile()){
System.out.println("File is created!");
}else{
System.out.println("File already exists.");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}