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;


public class JavaFilePermissions {

    public static void main(String[] args) {
        File file = new File("/Users/pankaj/");
        //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
        //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.


Leave a Reply

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

Generic selectors
Exact matches only
Search in title
Search in content