Java讀取resource文件/路徑的幾種方式
1. 說明
該文章轉載自 https://blog.csdn.net/oschina_40188932/article/details/78833754?utm_source=blogxgwz0,寫的很好 感謝解決我的需求,特此記錄一下
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.js
2.2 方式二
File directory = new File("");//參數為空
String courseFile = directory.getCanonicalPath()//標准的路徑 ;
String author =directory.getAbsolutePath()//絕對路徑;
在jdk1.1后就有了此方法獲取文件路徑的方式存在了)
示例路徑結果:E:\idea_work\sofn-qry-web
2.3 方式三
在web.xml配置如下代碼
<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不重復即可,調用如下
System.getProperty("evan.webapp");
//獲取的值類似E:\develop_tools\apache-tomcat-7.0.59\webapps\bookMobile