Java File Permissions

Filed Under: Java

Java File class contains methods to check file permissions for the application user. They also have some methods to set file permissions for the user and everybody else.

Java File Permissions

Here is a simple java program using File class permission methods. We will first check the file permissions for the user. Later on, we will change the file permissions for the application user and then for all the other users too.


package com.journaldev.files;

import java.io.File;

public class JavaFilePermissions {

    public static void main(String[] args) {
        File file = new File("/Users/pankaj/run.sh");
        //check file permissions for application user
        System.out.println("File is readable? "+file.canRead());
        System.out.println("File is writable? "+file.canWrite());
        System.out.println("File is executable? "+file.canExecute());
        //change file permissions for application user only
        file.setReadable(false);
        file.setWritable(false);
        file.setExecutable(false);
        //change file permissions for other users also
        file.setReadable(true, false);
        file.setWritable(true, false);
        file.setExecutable(true, true);
    }

}

Below image shows the output produced by the above application.

java file permissions, java get file permissions, java set file permissions

Note that setting File permissions is not versatile and if you are working on Java 7, you should use Java PosixFilePermission to set file permissions.

Also these File set permission methods return false if they are not able to set the file permissions. This can happen due to user privilege. For example, if I change the owner of my sample file to root, then all the set file permission method calls return false.

That’s all for java file permissions, how to check file permissions and how to set file permissions in java.

Reference: https://docs.oracle.com/javase/8/docs/api/java/io/File.html#setReadable-boolean-

Leave a Reply

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

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages