In this section, we will be showing how to change permission of a file in java particularly into read only. The sample source code is easy to understand. We will be using the setReadOnly method of File class under java.lang package. This is essential knowledge in setting up permission for files that you are creating.

Set file into read only in java

The following are the possible output of this program:

  • Successfully set file into read only
  • Setting the file to read only is not successful
  • File does not exist

The first and second sample output can be derived in getting the boolean return of method setReadOnly(). And then we can get the third output if the file input does not exists.

package com.javatutorialhq.tutorial;

import java.io.File;

public class MakeReadOnly {

	/**
	 * This java sample code shows
	 * how to set file into read only
	 * Property of teknoscope.com
	 * All Rights Reserved
	 * Version 1.0
	 * 07/03/2012
	 */
	public static void main(String[] args) {
        // create a File object as declared on the File constructor
		File file = new File("C:\\temp\\test.log");

		// check if the file exists
		if(file.exists()){
			// setting the file permission into read only
			boolean success = file.setReadOnly();
			if(success){
				System.out.println("Successfully set file into read only");
			}
			else{
				System.out.println("Setting the file to read only is not successful");
			}
		}
		else{
			System.out.println("File does not exists");
		}
	}

}

Sample Output:

It is to be expected that the filename declared on the File constructor, the physical file on your disk is set to read only. If the file exists before we run the program, we will see that the file is successfully set into read only mode.