如何使用Java設置只讀文件

一個文件可以設置為readOnly調用setReadOnly方法。

調用以下方法:

file.setReadOnly();

以下代碼創建一個File對象。 它測試它是否可讀可寫,結果寫入輸出。 然後調用setReadOnly方法,完成相同的測試,輸出顯示文件不是只讀的。

創建以下java文件:

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

參考文獻:

Class File

最近評論