Change the Read and Write Permissions of a File in Java

In Java, file permissions differ depending on the operating system: *nix, NTFS(windows) and FAT/FAT32. All of them have different file permissions.

Check if the permission allows to:
  • file.canExecute(): returns true if the file is executable, otherwise false.
  • file.canWrite(): returns true, if   The file is editable, otherwise false.
  • file.canRead(): returns true, if the file is readable, otherwise false.
Change file permission
  • file.setExecutable(boolean): Allow operations to be executed.
  • file.setReadable(boolean): Allow the reading of operations.
  • file.canRead(): allow write operations.

 
import java.io.File;
import java.io.IOException;

public class ExampleFilePermission
{
public static void main( String[] args )
{
File file = new File("test.txt");

if(file.exists()){
System.out.println("Execution allowed: " + file.canExecute());
System.out.println("Write allowed: " + file.canWrite());
System.out.println("Read Allowed: " + file.canRead());
}

file.setExecutable(false);
file.setReadable(false);
file.setWritable(false);

System.out.println("Execution allowed: " + file.canExecute());
System.out.println("Write allowed: " + file.canWrite());
System.out.println("Read Allowed: " + file.canRead());
}
}
Output:

 
Execution allowed: true
Write allowed: true
Read allowed: true
Execution allowed: false
Write allowed: false
Read allowed: false
Resources: