Java读取resource文件/路径的几种方式
1. 说明
该文章转载自 https://blog.csdn.net/oschina_40188932/article/details/78833754?utm_source=blogxgwz0,写的很好 感谢解决个人需求,特此记录一下java
2. 实现
2.1 方式一
//获取文件路径 String fileName = this.getClass().getClassLoader().getResource("文件名").getPath(); String fileUtl = this.getClass().getResource("文件名").getFile();
在项目打成jar后的状况下getPath()与getFile()返回参数及用法的基本相同具体差别大研究)
示例路径结果:/E:/idea_work/sofn-qry-web/target/classes/CityJson.jsweb
2.2 方式二
File directory = new File("");//参数为空 String courseFile = directory.getCanonicalPath()//标准的路径 ; String author =directory.getAbsolutePath()//绝对路径;
在jdk1.1后就有了此方法获取文件路径的方式存在了)
示例路径结果:E:\idea_work\sofn-qry-webspring
2.3 方式三
在web.xml配置以下代码apache
<context-param> <param-name>webAppRootKey</param-name> <param-value>evan.webapp</param-value> </context-param> <listener> <listener-class>org.springframework.web.util.WebAppRootListener</listener-class> </listener>
其中param-value的值能够随便赋值,只要保证同一个tomcat下不一样项目的param-value不重复便可,调用以下tomcat
System.getProperty("evan.webapp"); //获取的值相似E:\develop_tools\apache-tomcat-7.0.59\webapps\bookMobile