Java獲取resources下文件路徑的幾種方法及遇到的問(wèn)題
方法一:使用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);
問(wèn)題記錄
獲取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í) 是無(wú)法獲取到該文件具體的路徑的 我的解決方案如下:
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下文件路徑的幾種方法及遇到的問(wèn)題的文章就介紹到這了,更多相關(guān)Java獲取resources文件路徑內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Java的WeakHashMap源碼解析及使用場(chǎng)景詳解
這篇文章主要介紹了Java的WeakHashMap源碼解析及使用場(chǎng)景詳解,Map本身生命周期很長(zhǎng),需要長(zhǎng)期貯留內(nèi)存中,但Map中的Entry可以刪除,使用時(shí)可以從其它地方再次取得,需要的朋友可以參考下2023-09-09
java簡(jiǎn)單實(shí)現(xiàn)自定義日歷
這篇文章主要為大家詳細(xì)介紹了java簡(jiǎn)單實(shí)現(xiàn)自定義日歷,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-05-05
Java中通過(guò)Class類獲取Class對(duì)象的方法詳解
這篇文章主要給大家介紹了關(guān)于Java中通過(guò)Class類獲取Class對(duì)象的方法,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家學(xué)習(xí)或者使用java具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面跟著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧。2017-08-08
java.sql.SQLTimeoutException異常的正確解決方法(親測(cè)有效!)
在我們編寫(xiě)程序的時(shí)候,有時(shí)候要進(jìn)行復(fù)雜的查詢時(shí),就會(huì)出現(xiàn)執(zhí)行sql時(shí)間過(guò)長(zhǎng),引起頁(yè)面執(zhí)行不了并提示執(zhí)行腳本超時(shí),這就是我們遇到超時(shí)異常,這篇文章主要給大家介紹了關(guān)于java.sql.SQLTimeoutException異常的正確解決方法,需要的朋友可以參考下2024-02-02

