File Check Permission

I am trying to check the resolution of a given file using the following code snippet.

public static void main(String[] args) { try{ FilePermission fp = new FilePermission("E:/test.txt", "read"); AccessController.checkPermission(fp); System.out.println("Ok to open socket"); } catch (AccessControlException ace) { System.out.println(ace); } 

So when I run it, it gives me the following exception:

java.security.AccessControlException: access denied ("java.io.FilePermission" "E:/test.txt" "read")

All rights are allowed on the file, but it throws me access to the thrown exception.

+5
source share
1 answer

Use the following snippet to check if you can read the file:

 boolean canRead = new java.io.File("E:/test.txt").canRead(); 

File.canRead checks to see if the SecurityManager (if any) has the ability to read the file and if you have read permissions on the file system.

Using AccessController.checkPermission(fp) will not throw an exception if there is a security context that implies . This is not the case when you simply run a Java application, as in your example.

+4
source

All Articles