String path = Platform.getBundle("你的項目名稱").getLocation();
path = path.substring(path.indexOf("/"), path.length()) + "根目錄下的文件名稱";
document = reader.read(new File(path));
上面這種方法變異運行沒有問題,但是打包生成插件之後運行,會報錯(空指針)
下面這種完美
例子1:
InputStream is = CommonUtil.class.getResourceAsStream("/youxml.xml");
document = reader.read(is);
例子2:
InputStream is = CommonUtil.class.getResourceAsStream("/text.txt");
reader = new BufferedReader(new InputStreamReader(is, "utf-8"));
while((line = reader.readLine()) != null){
}
小結:
String path = getResource("/th.txt").getPath();
File file = new File(path);// 不行 這樣得到的不是項目下的文件
InputStream is = getResourceAsStream("/th.txt"); // 當前項目根目錄下的th.txt