3

I just want some files to be read and written in my Java program. So I use java.security.SecurityManager to manage this, but it seems unsatisfactory.

The Main.java file is below

import java.io.*;
import java.util.*;
public class Main {
    static private final String INPUT = "in.txt";
    public static void main(String args[]) throws Exception {
        FileInputStream instream = null;
        BufferedReader reader = new BufferedReader(new FileReader(INPUT));
        String tempString = null;
        while ((tempString = reader.readLine()) != null) {
            System.out.println(tempString);
        }
    }
}

and the file /opt/java.policy like below

grant {
    permission java.io.FilePermission "./out.txt", "write";
};

Then I run

java -Xss64m -Xms16m -Xmx512m -Djava.security.manager -Djava.security.policy=/opt/java.policy Main

But there are no errors, the output is what the in.txt is. I tried other file and got the same result. Why does this happen?

user207421
  • 305,947
  • 44
  • 307
  • 483
islands
  • 43
  • 4
  • @XtremeBaumer Then you would be wrong, and you should have consulted the documentation before posting. There is no such action as 'revoke' in the Java Security Manager, for a start. – user207421 Jul 16 '18 at 11:03
  • 1
    @Michael There is no such thing as the `java.security.manager` package. – user207421 Jul 16 '18 at 11:09
  • 1
    @Michael Yes, there is such a thing as `java.security.manager`, but not a package. It is a JVM system property. – user207421 Jul 17 '18 at 00:58

1 Answers1

6

From the Javadoc:

Please note: Code can always read a file from the same directory it's in (or a subdirectory of that directory); it does not need explicit permission to do so.

Not that this is well-specified. Code isn't 'in' a directory: it is executed from a current working directory, and this appears to be what is meant.

user207421
  • 305,947
  • 44
  • 307
  • 483
  • @CarlosHeuberger Resources are not files. You hardly need permission to read your own resources, and that doesn't have anything to do with reading *files.* – user207421 Jul 16 '18 at 12:15
  • @CarlosHeuberger No. A resource is an entry in a JAR or WAR file. It does not exist on a file system; it is not a file; it cannot be read with `FileReader`; and therefore has nothing to do with this question. Moreover it would be idiotic for Java to provide a security system that interposed between an application and its own resources, and it does not do so. It is not, however, idiotic to provide a security system that interposes between an application and external files, and that is what this question and the Java Security Manager are both about. – user207421 Jul 16 '18 at 12:23