Java.io.File.setReadOnly() 方法
描述
java.io.File.setReadOnly() 方法将文件切换到只读模式并拒绝对文件的任何写操作。
声明
以下是 java.io.File.setReadOnly() 方法的声明 −
public boolean setReadOnly()
参数
NA
返回值
如果操作成功,此方法返回 true,否则返回 false。
异常
SecurityException − 如果安全管理器存在并且其方法拒绝对旧路径名或新路径名的写访问。
示例
下面的例子展示了 java.io.File.setReadOnly() 方法的使用。
package com.tutorialspoint;
import java.io.File;
public class FileDemo {
public static void main(String[] args) {
File f = null;
boolean bool = false;
try {
// create new File object
f = new File("C:/test.txt");
// returns true if file exists
bool = f.exists();
// if file exists
if(bool) {
// set file as read only
bool = f.setReadOnly();
// print
System.out.println("setReadonly() succeeded?: "+bool);
// checks whether the file is writable
bool = f.canWrite();
// prints
System.out.print("Is file writable?: "+bool);
}
} catch(Exception e) {
// if any error occurs
e.printStackTrace();
}
}
}
让我们编译并运行上面的程序,这将产生下面的结果 −
setReadonly() succeeded?: true Is file writable?: false

