Home  >  Core Java

Java FilePermission Example

By Arvind Rai, July 18, 2014
java.io.FilePermission has been introduced in JDK 1.2. FilePermission contains the permission related to a file or directory. All permission is associated with a path. A path is file path or a directory. A path can be as below.
1. D:/cp/- : "/-" indicates that permission will be associated with all sub directories and files recursively.
2. D:/cp/* : All directory and files within this directory.
The permission associated with path can be read, write, execute, delete and readlink. Now find the example.
FilePermissionDemo.java
package com.cp.io;
import java.io.FilePermission;
import java.io.IOException;
import java.security.PermissionCollection;
public class FilePermissionDemo {
	   public static void main(String[] args) throws IOException {
	      try{
	    	 String path = "D:/cp/test.txt";
	    	 FilePermission fp1 = new FilePermission("D:/cp/-", "read");
	    	 PermissionCollection pc = fp1.newPermissionCollection();
	         pc.add(fp1);
	         FilePermission fp2 = new FilePermission(path, "write");
	         pc.add(fp2);
		     if(pc.implies(new FilePermission(path, "read,write"))) {
			     System.out.println("Permission for "+path+" is read and write.");
  	         }else {
  	        	System.out.println("No read, write permission for "+path);
  	         }
	      }catch(Exception ex){
	         ex.printStackTrace();
	      }
	   } 
} 
In our example, a directory path is granted with read permission. And inside this path a file is granted with write permission.
POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS






©2019 concretepage.com | Privacy Policy | Contact Us