一個文件可以設置為readOnly調用setReadOnly方法。
file.setReadOnly();
以下代碼創建一個File對象。 它測試它是否可讀可寫,結果寫入輸出。 然後調用setReadOnly方法,完成相同的測試,輸出顯示文件不是只讀的。
import java.io.File; public class FileReadOnly { public static void main(String[] argv){ File file = new File( "V:/tmp/test.txt" ); boolean readable = file.canRead(); boolean writable = file.canWrite(); System.out.println( "The file is readable: " + readable + ", writable: " + writable ); file.setReadOnly(); readable = file.canRead(); writable = file.canWrite(); System.out.println( "The file is readable: " + readable + ", writable: " + writable ); } }
The file is readable: true, writable: true The file is readable: true, writable: false