Question:
How to grant access to a file with security manager enabled?
Code:
import java.security.*; import java.io.*; public class SecurityManagerTest { public static void main(String [] args) { SecurityManager sm = System.getSecurityManager(); if(sm != null){ try { sm.checkPermission(new FilePermission("/tmp/myfile.txt", "read,write")); System.out.println("Permission granted"); } catch (Exception e){ System.out.println(e.toString()); System.out.println("Permission NOT granted"); } } } }
Output:
$ java -Djava.security.manager SecurityManagerTest java.security.AccessControlException: access denied ("java.io.FilePermission" "/tmp/myfile.txt" "read,write") Permission NOT granted $ java -Djava.security.manager -Djava.security.policy=./sample.policy SecurityManagerTest Permission granted $ cat ./sample.policy grant { permission java.io.FilePermission "/tmp/myfile.txt", "read,write"; };