Java - Check if a file is read only

Posted on November 3, 2016


The canWrite() method of the File class is used to check whether the file is writable or not. This method return true if and only if the file system actually contains a file and the application is allowed to write to the file; otherwise false.

Here is an example of File.canWrite() .

ReadOnlyFileExample.java

package com.boraji.tutorial.io;

import java.io.File;

/**
 * @author imssbora
 * ReadOnlyFileExample.java
 * Nov 3, 2016
 */
public class ReadOnlyFileExample {
	public static void main(String[] args) {
		File file=new File("file.txt");
		if(file.exists()){
			if(!file.canWrite()){
				System.out.println("File is readonly");
			}else{
				System.out.println("File is not readonly");
			}
		}else{
			System.out.println("File does not exist.");
		}
	}
}

Output

File is readonly