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 .