Setting the file permissions in Java is OS specific. Each type of file system have different kind of file systems. Java provides the very generic solution to set the file permissions for all kind of file systems. This example demonstrates how to set file permissions to a file in the Linux operating system using Java program. I have worked on Ubuntu OS for this example. However, the example would be the same for all operating systems with the change of path.
For each file, there are three types of permissions are associated with the File object,
- Read – Can you read the file?
- Write – Can you write on the file?
- Execute – Can you execute the file?
For the above operations, there is corresponding methods available in the file class. All these methods returns true or false depends on the actual permission of that file.
- file.canRead()
- file.canWrite()
- file.canExecute()
The following methods can be used for setting the permissions.
- file.setReadable(true)
- file.setWritable(true)
- file.setExecutable(true)
Lets look at the following example to understand the file permissions in Java.
FilePermissionsExample.java
package javabeat.net.core; import java.io.File; import java.io.IOException; public class FilePermissionsExample { public static void main(String[] args) { try { File file = new File("/var/www/license.txt"); if (file.exists()) { System.out.println("Execute permission : " + file.canExecute()); System.out.println("Write permission : " + file.canWrite()); System.out.println("Read permission : " + file.canRead()); } file.setExecutable(true); file.setReadable(true); file.setWritable(true); System.out.println("Execute permission : " + file.canExecute()); System.out.println("Write permission : " + file.canWrite()); System.out.println("Read permission : " + file.canRead()); if (file.createNewFile()) { System.out.println("New file is created!"); } else { System.out.println("The above file already exists."); } } catch (IOException e) { e.printStackTrace(); } } }
Output…
Execute permission : false Write permission : false Read permission : false Execute permission : true Write permission : true Read permission : true The above file already exists.