How to make a file readonly or writable in java

This tutorial show how to make a file readonly. Since Java 1.2 the method file.setReadOnly() is present. Java 6 introduced a new method file.setWritable() both methods can make a file readonly.

Make a file readonly

We assume the /tmp/foo.txt file already exist on your system. We can set the file to read only using both the setReadOnly() method as the setWritable method. For confirmation we print the result to the console.

package com.memorynotfound.file;

import java.io.*;

public class MakeFileReadonly {

    public static void main(String... args){

        File file = new File("/tmp/foo.txt");

        file.setReadOnly();
        canWrite(file);

        file.setWritable(true);
        canWrite(file);

        file.setWritable(false);
        canWrite(file);
    }

    private static void canWrite(File file){
        if (file.canWrite()){
            System.out.println(file.getName() + " is writable");
        } else {
            System.out.println(file.getName() + " is readonly");
        }
    }
}

Output

foo.txt file readonly
foo.txt is writable
foo.txt is readonly

References

You may also like...