在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