我只想在我的Java程序中读取和写入一些文件.所以我使用java.security.SecurityManager来管理它,但似乎并不令人满意.
Main.java文件如下
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);
}
}
}
和文件/opt/java.policy如下
grant {
permission java.io.FilePermission "./out.txt", "write";
};
然后我跑了
java -Xss64m -Xms16m -Xmx512m -Djava.security.manager -Djava.security.policy=/opt/java.policy Main
但是没有错误,输出就是in.txt.我尝试了其他文件并获得了相同的结果.为什么会这样?
解决方法:
从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.
并不是说这是明确的.代码不在“目录”中:它是从当前工作目录执行的,这似乎是意思.