java讀取資源路徑的幾種實現方式
更新時間:2025年02月13日 08:49:37 作者:worilb
文章總結了Java讀取資源路徑的幾種方式,并指出了在JUnit測試文件和普通類中讀取資源路徑的區(qū)別,普通類中讀取資源路徑時,只返回主目錄,而JUnit測試文件中可以精確到所在模塊
java讀取資源路徑幾種方式
@Test public void path() throws IOException { System.out.println("用戶當前工作目錄"+System.getProperty("user.dir")); File directory = new File(""); String path2 = directory.getCanonicalPath(); System.out.println("當前工作目錄1:"+path2); String path3 = directory.getAbsolutePath(); System.out.println("當前工作目錄2:"+path3); String path = ClassUtils.getDefaultClassLoader().getResource("").getPath(); System.out.println("類加載器返回默認路徑:"+path); String path1 = ResourceUtils.getURL("classpath:").getPath(); System.out.println("ResourceUtils返回默認路徑:"+path1); String resourcePath = Thread.currentThread().getContextClassLoader().getResource("").getPath(); System.out.println("resourcePath返回默認路徑:"+resourcePath); ClassPathResource classPathResource = new ClassPathResource("excel/xx.xlsx"); System.out.println("ClassPathResource返回資源路徑:"+classPathResource.getURL()); URL resource = this.getClass().getClassLoader().getResource("excel/xx.xlsx"); System.out.println("類加載器返回資源路徑:"+resource.getPath()); URL url = ResourceUtil.getResource("excel/xx.xlsx"); System.out.println("ResourceUtil返回資源路徑:"+url.getPath()); }
注意:
以上是在Junit測試文件中的結果
工作可以精確到所在模塊,而普通類里打印是只有主目錄沒有模塊的。
如下:
public static void main(String[] args) throws IOException { System.out.println("用戶當前工作目錄"+System.getProperty("user.dir")); File directory = new File(""); String path2 = directory.getCanonicalPath(); System.out.println("當前工作目錄1:"+path2); String path3 = directory.getAbsolutePath(); System.out.println("當前工作目錄2:"+path3); }
總結
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
java開發(fā)之基于Validator接口的SpringMVC數據校驗方式
這篇文章主要介紹了java開發(fā)之基于Validator接口的SpringMVC數據校驗方式,文中附含詳細示例代碼,有需要的朋友可以借鑒參考下2021-09-09Spring MessageSource獲取消息不符合預期的問題解決方案
最近我參與的產品要做國際化支持,選擇了用Spring MessageSource來實現,這個Spring 框架提供的工具使用很簡單,網上有各種教程文章,這里不做贅述,只說一個實際遇到的問題及解決方案,需要的朋友可以參考下2024-01-01springboot多節(jié)點應用里的雪花算法唯一性詳解
雪花算法在單節(jié)點下唯一,但在多副本Kubernetes環(huán)境中可能重復,通過修改Pod名稱生成workId,解決了這個問題,同時避免了第三方組件和網絡請求,本文給大家介紹springboot多節(jié)點應用里的雪花算法唯一性,感興趣的朋友一起看看吧2024-12-12SpringBoot Starter機制及整合tomcat的實現詳解
這篇文章主要介紹了SpringBoot Starter機制及整合tomcat的實現,我們知道SpringBoot自己在“后臺”幫我們配置了很多原本需要我們手動去的東西,至于這個“后臺”是啥,就是Starter機制2022-09-09