Search code examples
javafilefile-permissions

Setting FilePermissions in Java


In my program i want to create some temporary directories namely Temp1 and Temp2.

I am currently working on Mac and i choose the place to create these directories as

/Users/your_account_username/Library/Application Support

This directory has the following File Permissions

> drwx------+  27 ib-mac-1  staff   918 May  7 19:01 Application Support

When i create Temp1 , i set read, write, execute permissions using the Java File API.

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

Somehow this is not helping me apply rwx to the directories, the created directories/files under them are taking the only drwxr-xr-x


Solution

  • File.setExecutable(boolean), File.setReadable(boolean) and File.setWritable(boolean) set only the owner permissions.

    As schmop says, there are variants where you can indicate that you want the permissions set for everyone (file.setReadable(true, false), etc).

    However, if you want precise control of the POSIX file permissions (setting different other and group permissions, for example), the easiest solution is to use Java 7. Java 7 added the Path interface and Paths and Files classes as a replacement for File. It provides the method Files.setPosixFilePermissions, which can give you precisely the file permissions you want.