在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
¥ 我要打赏
纠错/补充
收藏
加QQ群啦,易百教程官方技术学习群
注意:建议每个人选自己的技术方向加群,同一个QQ最多限加 3 个群。