How to set a File read-only using Java

A File can be set to readOnly calling the method setReadOnly.

Call the following method:

file.setReadOnly();

The following code, creates a File object. It tests if it is readable and writable, the results are written in the output. Then the method setReadOnly is called, the same tests are done and the output shows that the file is not read only.

Create the following java file:

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 output will be:

The file is readable: true, writable:  true
The file is readable: true, writable:  false

References:

Class File

Recent Comments