Set a File Read only in Java

An example on setting a file as read-only in Java using File class.


class SetReadOnly
public static void main(String args[])

// Create File object
File f=new File("");

// Mark this file read only

// Alternate method
// f.setReadable(true);

// Set Read only for owner only (2nd argument). If true, read only sets to owner only and not for other users if false read only for all users
// f.setReadable(true,true);

// Check whether it is read-only
System.out.println("Is this file read only (T/F)? "+f.canRead());



Is this file read only (T/F)? true

Note: To re modify the file, set it to writable. From command prompt, you can use attrib -r 

Posted by at on

Tags: Java IO,