public class Worker { private static String path; public static void main(String[] argv) throws Exception { path = "C:\\glassfish-4.1.1\\glassfish4\\README.txt"; Permission permission = new FilePermission(path, "read"); try { AccessController.checkPermission(permission); }catch (Exception e){ System.out.printf(String.valueOf(e)); } System.out.println(new FileInputStream(new File(path)).read()); } } 

This class will return something similar to

java.security.AccessControlException: access denied ("java.io.FilePermission" "C: \ glassfish-4.1.1 \ glassfish4 \ README.txt" "read") 84

Why was it possible to read from the file when there is no right for it!?

    1 answer 1

    To limit access to files in the file system, use methods of the class File

    • setExecutable()
    • setReadable()
    • setWritable()

    The example you give relates to the SecurityManager setting. This is a mechanism that allows a Java application to restrict access to certain resources (not only files). As an example, take the applets - SecurityManager does not give them access to the file system.

    Feel the difference - SecurityManager does not modify file permissions in the file system, but prohibits a Java application from performing certain actions with it. This is the meaning of the Permission class, and the classes inherited from it - they describe these actions.

    You read the file because in the JDK , by default, the SecurityManager disabled. You can check it this way:

     System.out.println(System.getSecurityManager()); // null, если отключен 

    Run the application with the VM key -Djava.security.manager and you will not be able to read the file until the corresponding security policy is configured. Default are in $JAVA_HOME/lib/security .

      public static void main(String[] args) throws FileNotFoundException, IOException { System.out.println(System.getSecurityManager()); String path = "D:/test/file.txt"; check(path, "read,write"); System.out.println(new FileInputStream(new File(path)).read()); } static void check(String path, String actions) { FilePermission perm = new FilePermission(path, actions); try { AccessController.checkPermission(perm); } catch (Exception e) { System.out.println(e); } } 

    For details, see the official documentation .