在java程式設計中,如何設定檔案為唯讀?
此範例演示如何使用File
類的file.setReadOnly()
和file.canWrite()
方法設定檔案為唯讀模式。
package com.yiibai;
import java.io.File;
public class ReadOnlyFile {
public static void main(String[] args) {
File file = new File("F:/worksp/javaexamples/java_files/myfile.txt");
System.out.println(file.setReadOnly());
System.out.println(file.canWrite());
}
}
執行上述範例程式碼,將產生以下結果 -
true
false
範例-2
以下是java中設定檔案唯讀的另一個範例
package com.yiibai;
import java.io.File;
import java.io.IOException;
public class ReadOnlyFile2 {
public static void main(String[] args) throws IOException {
File file = new File("F:/worksp/javaexamples/java_files/myfile.txt");
file.setReadOnly();
if (file.canWrite()) {
System.out.println("This file is writable");
} else {
System.out.println("This file is read only");
}
file.setWritable(true);
if (file.canWrite()) {
System.out.println("This file is writable");
} else {
System.out.println("This file is read only");
}
}
}
執行上述範例程式碼,將產生以下結果 -
This file is read only
This file is writable