Java File setReadOnly() method with examples

April 29, 2020 No comments Java IO File Examples setReadOnly

1. Introduction

The setReadOnly() method from Java IO sets the file or directory to be read-only. After running that method only read operations will be allowed.

2. Method signature

public boolean setReadOnly()

Parameters:

  • method does not take any parameter

Returns

  • true - true if the operation succeeded; false otherwise

Throws

  • SecurityException - when we do not have access to the file or directory

3. Examples

3.1. Code that sets the read-only flag for a file and try to write some text to it

package com.frontbackend.java.io;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;

public class FrontBackend {

    public static void main(String args[]) {

        try {
            File file = new File("/tmp/exists.txt");

            System.out.println(file.canRead()); // true
            System.out.println(file.canWrite()); // true

            if (file.setReadOnly()) {
                System.out.println("Set read-only flag successfully");
            }

            System.out.println(file.canWrite()); // false;

            BufferedWriter writer = new BufferedWriter(new FileWriter(file));
            writer.write("FrontBackend"); // (Permission denied)

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

The output:

true
true
Set read-only flag successfully
false
java.io.FileNotFoundException: /tmp/exists.txt (Permission denied)
    at java.io.FileOutputStream.open0(Native Method)
    at java.io.FileOutputStream.open(FileOutputStream.java:270)
    at java.io.FileOutputStream.<init>(FileOutputStream.java:213)
    at java.io.FileOutputStream.<init>(FileOutputStream.java:162)
    at java.io.FileWriter.<init>(FileWriter.java:90)
    at com.frontbackend.java.io.FrontBackend.main(FrontBackend.java:23)

After changing the read-only flag when we try to write some text to the file we faced an exception and that is, of course, expected behavior.

4. Conclusion

In this article, we presented the setReadOnly flag that marks the file or directory so that only read operation is allowed. After invoking this method the file or directory is guaranteed not to change until it is either deleted or marked to allow write access.

{{ message }}

{{ 'Comments are closed.' | trans }}