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