Java -Create a read only file

Posted on November 3, 2016


This example shows the use of setReadOnly() method of the File class. This method returns true if and only if the operation succeeded; false otherwise.

Here is an example to demonstrate this.

SetFileReadOnlyExample.java

package com.boraji.tutorial.io;

import java.io.File;
import java.io.IOException;

/**
 * @author imssbora
 * SetFileReadOnlyExample.java
 * Nov 3, 2016
 */
public class SetFileReadOnlyExample {
	public static void main(String[] args) throws IOException {
		File file=new File("file.txt");
		
		/*Create new file*/
		if(!file.exists()){
			file.createNewFile();
		}
		
		/*Set file read only*/
		if(file.setReadOnly()){
			System.out.println("File is set to readonly");
		}else{
			System.out.println("Unable to set file to readonly.");
		}
	}
}

Output

File is set to readonly