How to make a file read only in Java

  • 26 January 2017
  • ADM

 

How to make a file read only in Java - images/logos/java.jpg

 

This post will describe how to make a file read-only using Java.

For this there are two options:

  • using File.setReadOnly() method.
  • using File.setWritable(boolean) method.

The advantage of using File.setWritable(boolean) is that is working both ways: from writable to read-only and vice-versa.

Example

package com.admfactory.io;

import java.io.File;

public class FileReadOnly {

    public static void main(String[] args) {

	System.out.println("File Read-Only Example");
	System.out.println();
	File file = new File("D:\\admfactory.com\\dir1\\f1.txt");

	/** mark the file as read only, option available since Java 1.2 */
	file.setReadOnly();

	if (file.canWrite()) {
	    System.out.println(file.getAbsolutePath() + " is writable.");
	} else {
	    System.out.println(file.getAbsolutePath() + " is read only.");
	}

	/** mark the file as writable, option available since Java 1.6 */
	file.setWritable(true);

	if (file.canWrite()) {
	    System.out.println(file.getAbsolutePath() + " is writable.");
	} else {
	    System.out.println(file.getAbsolutePath() + " is read only.");
	}

	/** mark the file as read only again */
	file.setWritable(false);

	if (file.canWrite()) {
	    System.out.println(file.getAbsolutePath() + " is writable.");
	} else {
	    System.out.println(file.getAbsolutePath() + " is read only.");
	}

    }

}

Output

File Read-Only Example

D:\admfactory.com\dir1\f1.txt is read only.
D:\admfactory.com\dir1\f1.txt is writable.
D:\admfactory.com\dir1\f1.txt is read only.

 

References