|
file.setExecutable(boolean);
file.setReadable(boolean);
file.setWritable(boolean);
|
แต่อย่างไรก็ตาม ก่อนที่จะทำการกำหนดสิทธิ์ต่างๆให้ไฟล์นั้น เราควรจะเชคไฟล์ก่อนว่าให้ทำอะไรได้บ้างโดยใช้
|
file.canExecute();
file.canWrite();
file.canRead();
|
หมายเหตุ : ในระบบ *nix,
เราอาจจะต้องระบุประเภทสิทธิ์การเข้าถึงไฟล์เอง เช่นการกำหนดสิทธิ์ ให้เป็น
777 สำหรับไฟล์หรือ directory, อย่างไรก็ตาม Java IO
ไม่มีเมธอดสำหรับการกำหนดดังกล่าว(ในที่นี้อ้างอิงโดยใช้ Java 1.6)
แต่เราสามารถกำหนดได้โดยวิธีลัดแบบลูกทุ่ง ดังตัวอย่างโดยใช้คำสั่ง:
|
Runtime.getRuntime().exec("chmod 777 file");
|
ตัวอย่างการกำหนดสิทธิ์ให้กับไฟล์
package demo.file;
import java.io.File;
import java.io.IOException;
public class FilePermissionExample {
/**
* @param args
*/
public static void main(String[] args) {
try {
File file = new File("C:\\users\\nopphanan7\\newfile.txt");
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();
}
}
}
ผลลัพธ์ที่ได้คือ
Is Execute allow : true
Is Execute allow : true
Is Write allow : true
Is Read allow : true
Is Execute allow : true
Is Write allow : false
Is Read allow : true
File already exists.
ไม่มีความคิดเห็น:
แสดงความคิดเห็น