In this java example, we will be showing a source code that checks if file is read only or not. This is essentially important especially in dealing with file input out operations such as file copy, file deletion, etc. This file read only check will enable us to preemptively handle possible exceptions. Like for example if we are dealing with file deletion, the code might fail in deletion since the file is read only. We can handle this scenario gracefully by checking if file is read only and then change the file permission.

Check if file is read only or not in java

The java source code presented here is straightforward making use of canWrite() method of file class. This method returns a boolean, true if we can write something on the file and false if it is not permitted. The filename of the file is declared in calling the File constructor.

package com.javatutorialhq.tutorial;

import java.io.File;

public class CheckReadOnly {

	/**
	 * This sample code shows
	 * how to check if file is read only
	 * Property of javatutorialhq.com
	 * All Rights Reserved
	 * Version 1.0
	 * 07/01/2012
	 */
	public static void main(String[] args) {
		File f = new File("C:\\temp\\test.log");
		if(f.exists()){
			if(!f.canWrite()){
				System.out.println("File "+f.getAbsolutePath() + " is read only");
			}
			else{
				System.out.println("We can write on file "+f.getAbsolutePath());
			}
		}
	}

}

Sample Output:

File C:\temp\test.log is read only

For testing purposes i have set the file C:\temp\test.log to check if the code on showing the output of the program if the file is read only or not.