Making a File Read-Only in Java

Learn to create a new file and make the 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);

3. Check if the File is Read-Only or Writable

In order to check if the file is writable or read-only, we can use canWrite() method of File class. This method returns:

  • true : the file is writable
  • false : the file is read-only
File file = new File("c:/temp/testReadOnly.txt");

System.out.println("File is writable : " + file.canWrite()); // true

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

System.out.println("File is writable : " + file.canWrite()); // false

Happy Learning !!

Sourceocde on Github

Comments

Subscribe
Notify of
guest
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.