java

How to make a File Read-Only in Java

In this tutorial, we are going to see how to make a file read-only in Java. So we will use the setReadOnly() method which is part of java.io.File to make a file read-only. Since JDK 1.6, setWritable() method is provided to make a file writable again.
 

Program to make a File Read-Only in Java
import java.io.*;

public class Main
{
    public static void main(String[] args) throws IOException
    {
    	File f = new File("C:\\Users\\PC\\Desktop\\test.txt");
    	
    	//make the File Read-Only
    	f.setReadOnly();
    	
    	if(f.canWrite()){
    	     System.out.println("This file is writable");
    	}else{
    	     System.out.println("This file is read-only");
    	}   	
    }
}

Output:

This file is read-only

 

 

Program to make the file writable
import java.io.*;

public class Main
{
    public static void main(String[] args) throws IOException
    {
    	File f = new File("C:\\Users\\PC\\Desktop\\test.txt");
    	
    	//make the file writable
    	f.setWritable(true);
    	
    	if(f.canWrite()){
    	     System.out.println("This file is writable");
    	}else{
    	     System.out.println("This file is read-only");
    	}   	
    }
}

Output:

This file is writable
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *