Java check or set read only file

Let’s consider a java code for testing if a file is read-only and setting it writable if it is possible.


Check if file is read-only

private static boolean isReadOnly(File file) {
    return !file.canWrite();
}

Make file writable

Since java 1.6, it is possible to change file’s writable attribute:

private static boolean setWritable(File file) {
    return file.setWritable(true);
}

Mark file as read-only

private static boolean setReadOnly(File file) {
    return file.setReadOnly();
}

Complete example

In a complete example, we will create a temporary file which will be mark writable or read-only randomly. Then, we will check if it’s read-only and mark it the opposite state.

import java.io.File;
import java.io.IOException;
import java.util.Random;

/**
 * @author Denis Migol
 */
public class FileReadOnlyExample {
    private static boolean isReadOnly(File file) {
        return !file.canWrite();
    }

    private static boolean setWritable(File file) {
        return file.setWritable(true);
    }

    private static boolean setReadOnly(File file) {
        return file.setReadOnly();
    }

    public static void main(String[] args) throws IOException {
        File file = File.createTempFile("testReadOnly", null);
        file.deleteOnExit();
        file.setWritable(new Random().nextBoolean());

        if (isReadOnly(file)) {
            System.out.println("readonly");
            if (setWritable(file)) {
                System.out.println("set writable");
            }
        } else {
            System.out.println("writable");
            if (setReadOnly(file)) {
                System.out.println("set readonly");
            }
        }
    }
}

Outputs

Output when the file was marked writable:

writable
set readonly

Output when the file was marked read-only:

readonly
set writable