方法一:

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根目录的路径

posted on 2017-11-06 14:21  Godfrey富高贵  阅读(4725)  评论(0编辑  收藏  举报