Skip to content

Make file read only Java example

Make file read only Java example shows how to make file read only in Java. The example also shows how to open, read and write read only file.

How to make a file read-only in Java?

Java File class provides various methods to handle files. Use the setReadOnly method of the File class to make the file read-only.

This method sets the file or directory denoted by the file object to read-only.  It returns true if the operation was successful, false otherwise.

Example

Output

Note: This method may throw the SecurityException if there is no write access to the file.

How to check if the file is read-only or writable in Java?

Use the canWrite method of the File class to check if the file or directory is read-only.

This method returns true if the file or directory denoted by the file object can be written, false if there is no write permission to the file.

Output

How to make a read-only file writable in Java?

You can use setWritable method of the File class to make a read-only file writable in Java.

This method sets the file or directory denoted by the file object to writable. It returns true if the operation was successful, false otherwise.

Output

Note: The setWritable method is only available for Java 6 and later versions.

How to write a read-only file in Java?

If you try to write to a read-only file, it will throw the FileNotFoundException as given in the below example.

Output

Before you start writing to the file, always make sure that it is writable. If it is not writable, use the setWritable method to make the read-only file writable first.

Output

This example is a part of the Java File tutorial with examples.

Please let me know your views in the comments section below.

About the author

Leave a Reply

Your email address will not be published.