java

How to change the permissions of a file in Java

In this tutorial, we are going to see how to change the permissions of a file in Java. Java provides a number of methods for checking and changing the permissions of a file. File permissions should be changed when the user wants to restrict the operations allowed on a file.
 

Program to display the permissions of the current file
import java.io.*; 
  
public class Main 
{ 
    public static void main(String[] args) 
    {
        File f = new File("C:\\Users\\PC\\Desktop\\test.txt"); 
          
        //Display the permissions associated with the file
        System.out.println("Executable: " + f.canExecute()); 
        System.out.println("Read: " + f.canRead()); 
        System.out.println("Write: "+ f.canWrite()); 
    } 
}

Output:

Executable: true
Read: true
Write: true

 

 

Program to change the permissions of a file in Java
import java.io.*; 
  
public class Main 
{ 
    public static void main(String[] args) 
    {
        File f = new File("C:\\Users\\PC\\Desktop\\test.txt"); 
         
        // Change permissions
        f.setExecutable(true);
        f.setReadable(true);
        f.setWritable(false); 
		  
        // Display the permissions associated with the file
        System.out.println("Exécutable: " + f.canExecute()); 
        System.out.println("Lecture: " + f.canRead()); 
        System.out.println("Ecriture: "+ f.canWrite()); 
    } 
}

Output:

Executable: true
Read: true
Write: false
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 *