1. Introduction
In this article, we are going to show how to create a read-only file in Java. We will use methods available in Java IO and platform-dependent command executed using Runtime.getRuntime().exec()
.
This article is a part of the Java IO Tutorial.
2. Using java.io.File.setReadOnly()
method
One method to make a file read-only in Java is to use setReadOnly()
method that is available on File
class. The method returns a boolean value that tells if the operation was successful or not. In the following example we set a read-only file for a file located on /tmp/test.txt
:
If file exists and the operation of setting the read-only flag ends successfully, the output will be like the following:
3. Using java.io.File.setWritable()
method
We can use setWriteable()
method with true
parameter to set read-only flag on the file. In the following example, we show how to use it, additionally, we used file.canWrite()
method to verify if we can write to the file:
The output will be the following:
4. Using native command
To change read-only parameter on file in Java we can also use Runtime.getRuntime()
however this approach is not recommended. The following examples show how to set read-only flag on Linux and Windows:
On Linux we can use chmod 0444
command:
On Windows use attrib
command:
5. Conclusion
In this article, we presented ways to create a read-only file in Java. There are several methods in Java IO we can use. The most recommended are those available directly in Java API, using a native command like chmod
fired with Runtime.getRuntime().exec()
is not the best option.
Like always the examples used in this article are available under our GitHub Repository.
{{ 'Comments (%count%)' | trans {count:count} }}
{{ 'Comments are closed.' | trans }}