Java 程序,将文件属性改为可写
假设我们的文件是“input.txt”,它被设置为只读 −
File myFile = new File("input.txt"); myFile.createNewFile(); myFile.setReadOnly();
现在,将上述文件设置为可写 −
myFile.setWritable(true);
之后,可以使用 canWrite() 来检查文件是否可写。
示例
import java.io.File; public class Demo { public static void main(String[] args) throws Exception { File myFile = new File("input.txt"); myFile.createNewFile(); myFile.setReadOnly(); if (myFile.canWrite()) { System.out.println("Writable!"); } else { System.out.println("Read only mode!"); } // set file to writable myFile.setWritable(true); if (myFile.canWrite()) { System.out.println("Writable!"); } else { System.out.println("Read only mode!"); } } }
输出
Read only mode! Writable!
广告