Java Set File Permissions using PosixFilePermission

Filed Under: Java

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 sets of users – owner and everybody else only. You can’t set different file permissions for group and other users.

Java Set File Permissions

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

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

FilePermissions.java


package com.journaldev.files;

import java.io.File;
import java.io.IOException;
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
        file.setExecutable(false);
        file.setReadable(false);
        file.setWritable(true);
        
        //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
        perms.add(PosixFilePermission.OWNER_READ);
        perms.add(PosixFilePermission.OWNER_WRITE);
        perms.add(PosixFilePermission.OWNER_EXECUTE);
        //add group permissions
        perms.add(PosixFilePermission.GROUP_READ);
        perms.add(PosixFilePermission.GROUP_WRITE);
        perms.add(PosixFilePermission.GROUP_EXECUTE);
        //add others permissions
        perms.add(PosixFilePermission.OTHERS_READ);
        perms.add(PosixFilePermission.OTHERS_WRITE);
        perms.add(PosixFilePermission.OTHERS_EXECUTE);
        
        Files.setPosixFilePermissions(Paths.get("/Users/pankaj/run.sh"), perms);
    }

}

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

You can checkout more Java IO examples from our GitHub Repository.

Comments

  1. SIMIYU CYPHRENE SABUNI says:

    Hi Pankaj, I still experience problems with doing this for windows.
    Will you have a solution for me please
    This is my Error:
    Exception in thread “main” java.lang.UnsupportedOperationException
    at java.nio.file.Files.setPosixFilePermissions(Files.java:1989) at java.nio.file.Files.setPosixFilePermissions(Files.java:1989)
    at planningstar.FilePermissions.main(FilePermissions.java:58)

  2. Ram Mahesh says:

    Hi Pankaj… What is that run.sh file.. What is the function of that? Where should that file be.

    1. Ram Mahesh says:

      Sorry Pankaj.. I got it..
      I have another doubt. When i run the above code, i get the following error:Exception in thread “main” java.lang.UnsupportedOperationException
      at java.nio.file.Files.setPosixFilePermissions(Files.java:1989)
      Kindly help me.

      1. Dvir says:

        Ram, you are running this code on windows – not supporting posix

  3. Terence Alderson says:

    I really love your posts. I find them incredibly helpful for getting fast and succinct information on pieces of java I don’t know very well.

    I was just looking up problems with the Bill Pugh thread safe singleton and came across your examples of the singleton. Extremely helpful thanks.

    Regards.

  4. Amit Sharma says:

    Hi Pankaj, i am learning java (Fresher)from your website and i am your Fan, i want to create a swing GUI Apps that Ping multiple IP addresses. the following code are written by me as a console programming. this program create a folder in Desktop and save ping result in .txt file. but there is only problem object of only first class execute or object of second class run but not together run only on file created at one time …please help me sit ..
    Many thanks in advance
    amitmcagju@gmail.com
    *************************Main Class*******************
    import java.io.*;
    public class Ping_An_IP
    {
    public static void main(String[] args)
    {

    FolderCreater folderCreate=new FolderCreater();
    String p=folderCreate.createNewFolder();

    String ip = “10.60.90.10 -t”;
    String pingCmd = “ping ” + ip;
    String ip1 = “10.60.90.25 -t”;
    String pingCmd1 = “ping ” + ip1;

    PingFirstIP fIP= new PingFirstIP(p,pingCmd);

    PingSecondIP sIP=new PingSecondIP(p,pingCmd1);
    }
    }

    second class

    import java.io.*;
    class PingFirstIP
    {
    String folderPath=null;
    String fIP=null;
    String th1Name=null;
    boolean flag=true;

    String pR=””;

    CurrentTimeProvider now=new CurrentTimeProvider();

    public PingFirstIP(String folderPath,String fIP)
    {

    this.folderPath=folderPath;
    this.fIP=fIP;
    call2();

    }

    public void call2()
    {

    try
    {
    while(flag)
    {
    Runtime runtime = Runtime.getRuntime();
    Process process = runtime.exec(fIP);

    BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
    String line;
    PrintStream ps = new PrintStream(folderPath+”\\\\”+”ping.txt”);
    System.setOut(ps);

    while ((line = in.readLine()) != null)
    {

    System.out.println(line+” “+now.getCurrentTime());
    pR += line;

    //System.out.println(t1.getName());
    Thread.sleep(100000);
    }
    in.close();
    }
    }
    catch(Exception e)
    {
    System.out.println(e);
    }
    }

    }

    Third Class

    import java.io.*;
    class PingSecondIP
    {
    String folderPath1=null;
    String sIP=null;
    String th2Name=null;
    boolean flag1=true;
    String pR1=””;

    CurrentTimeProvider now=new CurrentTimeProvider();

    public PingSecondIP(String folderPath1,String sIP)
    {

    this.folderPath1=folderPath1;
    this.sIP=sIP;
    call1();

    }

    public void call1()
    {

    try
    {
    while(flag1)
    {
    Runtime runtime1 = Runtime.getRuntime();
    Process process1 = runtime1.exec(sIP);

    BufferedReader in1 = new BufferedReader(new InputStreamReader(process1.getInputStream()));
    String line1;
    PrintStream ps1 = new PrintStream(folderPath1+”\\\\”+”ping1.txt”);
    System.setOut(ps1);

    while ((line1 = in1.readLine()) != null)
    {

    System.out.println(line1+” “+now.getCurrentTime());
    pR1 += line1;
    Thread.sleep(100000);

    }
    in1.close();
    }
    }
    catch(Exception e)
    {
    System.out.println(e);
    }
    }

    }

    1. Pankaj says:

      I will need sometime to check your program, will get back to you.

  5. Medeea says:

    Hello! I have an application that saves data into xml files.I need something to prevent the user from renaming these files.I’m kinda new at this and google seems to be not as helpfull as usual.Could you suggest something that I can use?

    1. Pankaj says:

      remove the permission for the file.

  6. Avi says:

    Hi, I want to set permissions on a directory for a particular “user”. Would you have some ideas on how to do that using java IO? I am currently on Java 6.

    Thanks in advance.

    1. Pankaj says:

      You can use Runtime to execute script to give user based permissions if you are on Java 6.

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