RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Jun 1, 2021

Exploring the Java File Permission Class

Java has a special class that is used to represent access to files and directories, named java.io.FilePermission. The class can be used to create permissions and assign those permissions to files.

The java.io.FilePermission class has five methods associated with it:

  • equals(Object FP_obj): Used to determine if the FilePermission objects are equal or not.
  • getActions():: Gets the action of FilePermission object (example: read, write, delete, execute, readlink) and returns it as a canonical string.
  • hashCode(): returns a hashcode for the FilePermission object.
  • implies(Permission arg): Returns whether the FilePermission has an argumented permission or not.
  • newPermissionCollection(): creates a PermissionCollection object that has the FilePermissionobjects.

Here is some Java code illustrating the use of the java.io.FilePermission class and java.security.PermissionCollection.:


import java.io.FilePermission;  
import java.security.PermissionCollection;  

public class FilePermissionsEx
	public static void main(String[] args) 
		FilePermissionsEx filePermissionsEx = new FilePermissionsEx();

	private void proceed()  
		String sourceFile = "/opt/FilePer/FilePermissionsEx.java";  
		String readPermission = "Read";
		String writePermission = "Write";
		String readWritePermission = "Read,Write";
		//Creating the read permission 
		FilePermission readFilePermission = new FilePermission(sourceFile, readPermission);  
		PermissionCollection permissionCollection = readFilePermission.newPermissionCollection();  
		//Associating the read permission to the permission collection
		//Creating the write permission 
		FilePermission writeFilePermission = new FilePermission(sourceFile, writePermission);  
		//Associating the write permission to the permission collection

		//Checking if read permission is granted to the file
		if(permissionCollection.implies(new FilePermission(sourceFile, readPermission))) 
			System.out.println(sourceFile + " is granted " + readFilePermission );
			System.out.println(sourceFile + " is not granted " + readFilePermission );
		//Checking if write permission is granted to the file
		if(permissionCollection.implies(new FilePermission(sourceFile, writePermission))) 
			System.out.println(sourceFile + " is granted " + writeFilePermission );
			System.out.println(sourceFile + " is not granted " + writeFilePermission );

You can expect the following output from our Java code snippet:

[root@mypc]# java FilePermissionsEx
/opt/FilePer/FilePermissionsEx.java is granted ("java.io.FilePermission" "/opt/FilePer/FilePermissionsEx.java" "read")
/opt/FilePer/FilePermissionsEx.java is granted ("java.io.FilePermission" "/opt/FilePer/FilePermissionsEx.java" "write")
MS Sridhar
Close Icon
Thanks for your registration, follow us on our social networks to keep up-to-date