How to set File Permissions in Java Easily using Java 7 PosixFilePermission

Java File class has the ability to set the file permissions but it’s not versatile. The biggest drawback is that you can divide file permissions into two set of users – owner and everybody else only. You can’t set different file permissions for group and other users.

Java 7 has introduced PosixFilePermission Enum and java.nio.file.Files includes a method setPosixFilePermissions(Path path, Set perms) that can be used to set file permissions easily.

Here is a simple program that clearly shows why PosixFilePermission is better.

package com.journaldev.files;

import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.attribute.PosixFilePermission;
import java.util.HashSet;
import java.util.Set;

public class FilePermissions {

     * File Permissions Java Example using File and PosixFilePermission
     * @param args
     * @throws IOException 
    public static void main(String[] args) throws IOException {
        File file = new File("/Users/pankaj/temp.txt");
        //set application user permissions to 455
        //change permission to 777 for all the users
        //no option for group and others
        file.setExecutable(true, false);
        file.setReadable(true, false);
        file.setWritable(true, false);
        //using PosixFilePermission to set file permissions 777
        Set<PosixFilePermission> perms = new HashSet<PosixFilePermission>();
        //add owners permission
        //add group permissions
        //add others permissions
        Files.setPosixFilePermissions(Paths.get("/Users/pankaj/"), perms);


From above example, it’s clear that PosixFilePermission provides more options and code is more readable. If you are using Java 7, you should use it for setting file permissions in java.

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Subscribe to JournalDev Newsletter
Get the FREE access to Monthly Newsletter and Free PDF eBooks
*No Spam Guaranteed. By entering your email address, you agree also subscribing to our newsletter.
Oops! - Something went wrong.
Few Copies Left: Java 8 Lambda Expressions PDF eBook Free Download Now
'Java Video Tutorial Series' at 83% Discount - Coupon Code '10ACHIEVE' Enroll Now
Advertisment ad adsense adlogger