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

Was this post helpful?

Join 7000+ Awesome Developers

Get the latest updates from industry, awesome resources, blog updates and much more.

* We do not spam !!

Leave a Comment

HowToDoInJava

A blog about Java and related technologies, the best practices, algorithms, and interview questions.