Table of Contents
In this post, we will see how to make a read only file in java. It is very simple. You need to just call java.io.File ‘s  setReadOnly() method.
When you run above program, you will get following output:
Java program:
When you run above program, you will get following output:
1) How to make a file read only
Java program:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
package org.arpit.java2blog; import java.io.File; public class FileHiddenMain { public static void main(String[] args) { System.out.println("-----------------"); // Read the file File configFile=new File("/Users/Arpit/Desktop/config.properties"); configFile.setReadOnly(); if(configFile.canWrite()) { System.out.println("Config file can be writtern"); } else { System.out.println("config file is read only"); } System.out.println("-----------------"); } } |
1 2 3 4 5 |
----------------- config file is read only ----------------- |
2) How to make it writable  again
If you have made file read only, you can make file writable again by using method setWritable(true).
This method is introduced in java 1.6.
Java program:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
package org.arpit.java2blog; import java.io.File; public class FileHiddenMain { public static void main(String[] args) { System.out.println("-----------------"); // Read the file File configFile=new File("/Users/Arpit/Desktop/config.properties"); configFile.setReadOnly(); if(configFile.canWrite()) { System.out.println("Config file can be written"); } else { System.out.println("config file is read only"); } System.out.println("-----------------"); System.out.println("Making config file writable again"); // this method is available from jdk 1.6 configFile.setWritable(true); if(configFile.canWrite()) { System.out.println("Config file can be written"); } else { System.out.println("config file is read only"); } System.out.println("-----------------"); } } |
1 2 3 4 5 6 7 8 |
----------------- config file is read only ----------------- Making config file writable again Config file can be written ----------------- |
Â
Was this post helpful?
Let us know if this post was helpful. Feedbacks are monitored on daily basis. Please do provide feedback as that\'s the only way to improve.