How to make a file read-only?
优质
小牛编辑
127浏览
2023-12-01
问题描述 (Problem Description)
如何将文件设为只读?
解决方案 (Solution)
此示例演示如何使用File类的file.setReadOnly()和file.canWrite()方法将文件设置为只读。
import java.io.File;
public class Main {
public static void main(String[] args) {
File file = new File("C:/java.txt");
System.out.println(file.setReadOnly());
System.out.println(file.canWrite());
}
}
结果 (Result)
上面的代码示例将产生以下结果。要测试该示例,首先在'C'驱动器中创建一个文件'java.txt'。
true
false
以下是java中只读文件的另一个示例示例
import java.io.File;
import java.io.IOException;
public class FileReadAttribute {
public static void main(String[] args) throws IOException {
File file = new File("c:/file.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");
}
}
}
上面的代码示例将产生以下结果。要测试该示例,首先在'C'驱动器中创建一个文件'java.txt'。
This file is read only
This file is read only