有时候我们需要创建只读文件,来保护我们一些信息,本文使用File类的setReadOnly()方法。 当且仅当操作成功时,此方法返回true; 否则此方法返回false。
下面是一个Java创建只读文件的例子。
文件:SetFileReadOnlyExample.java -
package com.codeinn.tutorial.io;
import java.io.File;
import java.io.IOException;
/**
* @author codeinn
* SetFileReadOnlyExample.java
* Nov 3 2016
*/
public class SetFileReadOnlyExample {
public static void main(String[] args) throws IOException {
File file=new File("file.txt");
/*Create new file*/
if(!file.exists()){
file.createNewFile();
}
/*Set file read only*/
if(file.setReadOnly()){
System.out.println("File is set to readonly");
}else{
System.out.println("Unable to set file to readonly.");
}
}
}
执行上面示例代码,得到以下结果:
File is set to readonly