Set File permissions in Java example
With this example we shall show you how to set file permissions with Java. This is a very important task to take into consideration when you’re working in a shared system. Although this operation is operation system specific, Java offers a generic API that you can use in all platforms.
As you know in UNIX systems you can go much further than just setting a file to be readable, writable or executable. You can set the permissions you want for all users and groups that share the system and not only for the owner of the file. For example you can do chmod 744 filename
. Java does not offer that kind of flexibility in UNIX environments, but you can always use : Runtime.getRuntime().exec("chmod 744 filename")
.
In short, all you have to do in order to find out or set file permissions in Java is:
- Use
File.canExecute()
,File.canWrite()
andFile.canRead()
methods to see the respective permissions of a specific file - Use
File.setReadable(boolean)
,File.setWritable(boolean)
andFile.setExecutable(boolean)
methods to set the respective permissions of a specific file
Let’s see the code:
package com.javacodegeeks.java.core; import java.io.File; import java.io.IOException; public class JavaFilePermissionsExample { public static void main(String[] args) { try { File scriptfile = new File("C:\\Users\\nikos7\\Desktop\\words"); if (scriptfile.exists()) { System.out.println("Is file executable: "+ scriptfile.canExecute()); System.out.println("Is file writable : "+ scriptfile.canWrite()); System.out.println("Is file readable : " + scriptfile.canRead()); } scriptfile.setReadable(true); scriptfile.setWritable(true); scriptfile.setExecutable(true); System.out.println("\nIs file executable : "+ scriptfile.canExecute()); System.out.println("Is file writable : " + scriptfile.canWrite()); System.out.println("Is file readable : " + scriptfile.canRead()); if (scriptfile.createNewFile()) { System.out.println("\nFile has been succesfully created"); } else { System.out.println("\nFile already exists!"); } } catch (IOException e) { e.printStackTrace(); } } }
Output:
Is file executable: true
Is file writable : false
Is file readable : true
Is file executable : true
Is file writable : true
Is file readable : true
File already exists!
This was an example of how to set and see the read, write and execute permissions of file in Java.
Will the operation fail if the user/Application does not have permission to change the access permissions of this abstract path name