islands
islands

Reputation: 43

Why any file can be read with using java.security.SecurityManager in java?

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?

Upvotes: 3

Views: 532

Answers (1)

user207421
user207421

Reputation: 310840

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.

Upvotes: 6

Related Questions