Java獲取resources下文件路徑的幾種方法及遇到的問題
更新時(shí)間:2023年12月14日 11:39:53 作者:白大鍋
這篇文章主要給大家介紹了關(guān)于Java獲取resources下文件路徑的幾種方法及遇到的問題,在Java開發(fā)中經(jīng)常需要讀取項(xiàng)目中resources目錄下的文件或獲取資源路徑,需要的朋友可以參考下
方法一:使用ClassLoader.getResource()方法
String filePath = "path/to/file.txt"; URL resourceUrl = getClass().getClassLoader().getResource(filePath); String resourcePath = resourceUrl.getPath();
方法二:使用ClassLoader.getResourceAsStream()方法
String filePath = "path/to/file.txt"; InputStream inputStream = getClass().getClassLoader().getResourceAsStream(filePath);
方法三:使用Class.getResource()方法
String filePath = "path/to/file.txt"; URL resourceUrl = getClass().getResource(filePath); String resourcePath = resourceUrl.getPath();
方法四:使用Class.getResourceAsStream()方法
String filePath = "path/to/file.txt"; InputStream inputStream = getClass().getResourceAsStream(filePath);
問題記錄
獲取resources目錄下某文件路徑并返回
public String getResourcesPath(String filePath) { String resourcePath=null; try { Resource resource = new ClassPathResource(filePath); Path path = resource.getFile().toPath(); resourcePath=path.toString(); } catch (IOException e) { throw new RuntimeException(e); } return resourcePath; }
此處也能獲取到文件路徑 僅限本地 當(dāng)jar包時(shí) 是無法獲取到該文件具體的路徑的 我的解決方案如下:
public String getResourcesPath(String filePath) { String resourcePath=null; File file = new File(filePath); try { Resource resource = new ClassPathResource(filePath); InputStream inputStream = resource.getInputStream(); FileUtils.copyInputStreamToFile(inputStream, file); resourcePath=file.getAbsolutePath(); } catch (IOException e) { throw new RuntimeException(e); } return resourcePath; }
從流中獲取
總結(jié)
到此這篇關(guān)于Java獲取resources下文件路徑的幾種方法及遇到的問題的文章就介紹到這了,更多相關(guān)Java獲取resources文件路徑內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
java.sql.SQLTimeoutException異常的正確解決方法(親測有效!)
在我們編寫程序的時(shí)候,有時(shí)候要進(jìn)行復(fù)雜的查詢時(shí),就會(huì)出現(xiàn)執(zhí)行sql時(shí)間過長,引起頁面執(zhí)行不了并提示執(zhí)行腳本超時(shí),這就是我們遇到超時(shí)異常,這篇文章主要給大家介紹了關(guān)于java.sql.SQLTimeoutException異常的正確解決方法,需要的朋友可以參考下2024-02-02