方法一:
String path = this.getClass().getProtectionDomain().getCodeSource().getLocation().getPath();
path = path.substring(0,path.indexOf("/WEB-INF"));
String fileName =path+"/xxx.txt";
方法二:
這個就比較簡單了,直接看代碼:
BufferedReader br = new BufferedReader(new InputStreamReader(this.getClass().getResourceAsStream("/4_4.xml"),"utf-8"));
String s = "";
StringBuffer sb = new StringBuffer("");
while ((s = br.readLine()) != null) {
sb.append(s + "\r\n");
}
br.close();
方法三:
inStream=DaoFactory.class.getClassLoader().getResourceAsStream("com/jdbc/dao/dao.properties");
第三種是最本質的做法,前兩種也是基於第三種去實現的。JVM會使用Bootstrap Loader去加載資源文件。所以路徑還是這種相對於工程的根目錄即"com/jdbc/dao/dao.properties"(不需要“/”)
InputStream inStream = DaoFactory.class.getResourceAsStream("dao.properties"); --采用的相對路徑
inStream=DaoFactory.class.getResourceAsStream("/com/jdbc/dao/dao.properties") --采用絕對路徑,絕對路徑是相對於classpath根目錄的路徑
