Making a File Read-Only in Java

Learn to make a file read-only in Java. A read-only file can be opened for reading, but we cannot modify or delete the file contents. A read-only file or directory can be deleted if the file system permits.

1. Using File.setReadOnly()

The setReadOnly() method marks the file or directory specified in the path so that only read operations are allowed.

The method returns true if and only if the operation succeeded; false otherwise

File file = new File("c:/temp/testReadOnly.txt");

// Mark it read only
boolean success = file.setReadOnly();

2. Using File.setWritable(false)

The setWritable() is a convenient method to set the owner’s write permission for this abstract pathname.

It returns true if the operation succeeded. The operation will fail with SecurityException if the user does not have the required permissions.

File file = new File("c:/temp/testReadOnly.txt");

// Mark it read only
boolean success = file.setWritable(false);

Happy Learning !!

Sourceocde on Github

Leave a Reply

0 Comments
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions, and frequently asked interview questions.