How can I change a file attribute to read only?

This code demonstrate how we can modify file attribute to be read only. File class has a setReadOnly() method to make file read only and a canWrite() method to know whether it is writable or not.



public class FileReadOnlyExample {
    public static void main(String[] args) throws Exception {
        File file = new File("ReadOnly.txt");

        // Create a file only if it doesn't exist.

        // Set file attribute to read only so that it cannot be written

        // We are using the canWrite() method to check whether we can
        // modified file content.
        if (file.canWrite()) {
            System.out.println("File is writable!");
        } else {
            System.out.println("File is in read only mode!");

This code snippet print the following output:

File is in read only mode!


Programmer, runner, recreational diver, live in the island of Bali, Indonesia. Mostly programming in Java, creating web based application with Spring Framework, Hibernate / JPA. Support me by donating >> here <<.

Leave a Reply