Making a file read only is very easy in java. In this tutorial, we will learn following three things.
1) How to make a file read only
2) How to check whether the existing file is in read only mode or not
3) How to make a read only file writable in java.
1) Changing file attributes to read only
To make a file read only, we can use setReadOnly()
method of File class. It returns a boolean value which we can further use to verify whether the operation got successful or not, same way as I did in the below program. As you can see that in the below program, I am changing the file attributes to read only of file “Myfile.txt” which is present in “C drive” of my computer.
import java.io.File; import java.io.IOException; public class ReadOnlyChangeExample { public static void main(String[] args) throws IOException { File myfile = new File("C://Myfile.txt"); //making the file read only boolean flag = myfile.setReadOnly(); if (flag==true) { System.out.println("File successfully converted to Read only mode!!"); } else { System.out.println("Unsuccessful Operation!!"); } } }
Output:
File successfully converted to Read only mode!!
2) Check whether the file is writable or read only
In order to check the file attributes, we can use canWrite()
method of file class. This methods returns true if the file is writable else it returns false. As I am performing the operation on the file “Myfile.txt” which I already set to read only in the previous program, I am getting output as “File is read only”.
import java.io.File; import java.io.IOException; public class CheckAttributes { public static void main(String[] args) throws IOException { File myfile = new File("C://Myfile.txt"); if (myfile.canWrite()) { System.out.println("File is writable."); } else { System.out.println("File is read only."); } } }
Output:
File is read only.
3) How to make a read only file writable in java
To make a read only file to writable file, we can use setWritable()
method. This method can also be used to make a file read only.
file.setWritable(true)
: To make file writable.
file.setWritable(false)
: To make file read only.
import java.io.File; import java.io.IOException; public class MakeWritable { public static void main(String[] args) throws IOException { File myfile = new File("C://Myfile.txt"); //changing the file mode to writable myfile.setWritable(true); if (myfile.canWrite()) { System.out.println("File is writable."); } else { System.out.println("File is read only."); } } }
Output:
File is writable.
Leave a Reply