Java IO

Make file read only Java example

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

How to make file read only in Java?

Java File class provides various methods to handle files. Use setReadOnly method of the File class to make 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.

Make file read only Java example

Output

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

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

Use 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 read only file writable in Java?

You can use setWritable method of the File class to make 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: setWritable method is only available for Java 6 and later versions.

How to write read only file in Java?

If you try to write to read only file, it will throw an exception as given in below example.

Output

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

Output

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

Tags
Join 1000+ fellow learners! Enter your email address below: