获取web项目根目录下的文件,读取web项目根目录下的某个文件


方法一:

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


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM