For making a file read-only in Java, we can use any one of the given below APIs.
- java.io.File.setReadOnly()
- java.io.File.setWritable(false)
- Runtime.getRuntime().exec()
The Runtime.getRuntime().exec()
is platform-specific because of the system command we need to pass to it as parameter. The other two methods will work fine in most cases.
If you want to change Linux/Unix specific file properties e.g. using “chmod 775” then Java does not provide any way to do it.
1. Make file read only with File.setReadOnly()
The setReadOnly()
method marks the file or directory specified in path so that only read operations are allowed.
private static void readOnlyFileUsingNativeCommand() throws IOException { File readOnlyFile = new File("c:/temp/testReadOnly.txt"); //Mark it read only readOnlyFile.setReadOnly(); }
2. Use java.io.File.setWritable(false) method
setWritable()
is a convenience method to set the owner’s write permission for this abstract pathname.
private static void readOnlyFileUsingSetWritable() throws IOException { File readOnlyFile = new File("c:/temp/testReadOnly.txt"); //Mark it read only readOnlyFile.setWritable(false); }
3. Execute a native command (platform dependent)
exec()
executes the specified command and arguments in a separate process in the operating system.
private static void readOnlyFileUsingSetReadOnly() throws IOException { File readOnlyFile = new File("c:/temp/testReadOnly.txt"); //Mark it read only in windows Runtime.getRuntime().exec("attrib " + "" + readOnlyFile.getAbsolutePath() + "" + " +R"); }
Happy Learning !!