Java如何讀取jar包中的resource資源文件
1、需求
在Java項(xiàng)目中,需要讀取resource資源目錄下的文件,以及遍歷指定資源目錄下的所有文件,并且在讀取文件時(shí)保留文件相對(duì)路徑。
2、問(wèn)題
在IDEA中運(yùn)行時(shí),可以獲取并遍歷指定資源,但是將Java項(xiàng)目打成jar包運(yùn)行后,就無(wú)法獲取resource資源目錄下的文件。
3、IDEA讀取resource資源
編譯后,資源文件放在target目錄下,每一個(gè)資源文件實(shí)實(shí)在在存在于磁盤中。
3.1、方法1
直接通過(guò)絕對(duì)路徑讀取,如果file是目錄,也可以通過(guò)listFiles遞歸遍歷目錄下文件:
String absolutePath = "資源文件絕對(duì)路徑";
File file = new File(absolutePath);
if (file.isDirectory()) {
? ? File[] children = file.listFiles();
}3.2、方法2
通過(guò)相對(duì)路徑讀?。?/p>
String path = "template"; ? ?//相對(duì)resource路徑
File file = ResourceUtils.getFile(ResourceUtils.CLASSPATH_URL_PREFIX + path);
if (file.isDirectory()) {
? ? File[] children = file.listFiles();
}4、打成jar包后讀取resource資源
以上兩種方法無(wú)法讀取jar包中的資源文件。
打成jar包后,jar包是一個(gè)單獨(dú)的文件而不是文件夾,所以通過(guò)文件路徑是無(wú)法定位到資源文件的。此時(shí),可通過(guò)類加載器讀取jar包中的資源文件。
4.1、讀取jar包中的資源文件
這種方式只能讀取jar包中單個(gè)文件,因?yàn)樽x取出來(lái)的是InputStream流,無(wú)法保留文件相對(duì)于resource的路徑,所以無(wú)法對(duì)jar包中資源進(jìn)行遍歷。
String path = "/resource相對(duì)路徑"; InputStream is = this.class.getResourceAsStream(path); byte[] buff = new byte[1024]; String filePath = "保存文件路徑"; String fileName = "保存文件名"; File file = new File(filePath + fileName); FileUtils.copyInputStreamToFile(is, file);
4.2、遍歷jar包資源目錄
以復(fù)制resource資源目錄為例,分別對(duì)本地和jar包中的資源進(jìn)行復(fù)制。
如下所示:
我要復(fù)制resource資源目錄下的template文件夾下的所有內(nèi)容;
然后保存到C:/Users/ASUS/Desktop/savePath文件夾下。
4.2.1、環(huán)境判斷
public static void main(String[] args) throws URISyntaxException {
? ? // Test為當(dāng)前類名
?? ?URI uri = Test.class.getProtectionDomain().getCodeSource().getLocation().toURI();
?? ?// tempPath: 文件保存路徑
?? ?String tempPath = "C:/Users/ASUS/Desktop/savePath";
?? ?String sourceDir = "template"; ?//資源文件夾
?? ?if (uri.toString().startsWith("file")) {
? ? ? ? // IDEA運(yùn)行時(shí),進(jìn)行資源復(fù)制
?? ??? ?copyLocalResourcesFileToTemp(sourceDir + "/", "*", tempPath + "/" + sourceDir);
?? ?} else {
?? ??? ?// 獲取jar包所在路徑
?? ??? ?String jarPath = uri.toString();
?? ??? ?uri = URI.create(jarPath.substring(jarPath.indexOf("file:"),jarPath.indexOf(".jar") + 4));
? ? ? ? // 打成jar包后,進(jìn)行資源復(fù)制
?? ??? ?Test.copyJarResourcesFileToTemp(uri, tempPath, "BOOT-INF/classes/" + sourceDir);
?? ?}
}4.2.2、復(fù)制本地項(xiàng)目的資源文件
/**
? ? ?* 復(fù)制本地資源文件到指定目錄
? ? ?* @param fileRoot ? ? ?需要復(fù)制的資源目錄文件夾
? ? ?* @param regExpStr ? ? 資源文件匹配正則,*表示匹配所有
? ? ?* @param tempParent ? ?保存地址
? ? ?*/
? ? public static void copyLocalResourcesFileToTemp(String fileRoot, String regExpStr, String tempParent) {
? ? ? ? try {
? ? ? ? ? ? ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
? ? ? ? ? ? Resource[] resources = resolver.getResources(fileRoot + regExpStr);
? ? ? ? ? ? for (Resource resource : resources) {
? ? ? ? ? ? ? ? File newFile = new File(tempParent, resource.getFilename());
? ? ? ? ? ? ? ? if (newFile.exists()) {
? ? ? ? ? ? ? ? ? ? newFile.delete();
? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? InputStream stream = null;
? ? ? ? ? ? ? ? try {
? ? ? ? ? ? ? ? ? ? stream = resource.getInputStream();
? ? ? ? ? ? ? ? } catch (Exception e) {
? ? ? ? ? ? ? ? ? ? // 如果resource為文件夾時(shí),會(huì)報(bào)異常,這里直接忽略這個(gè)異常
? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? if (stream == null) {
? ? ? ? ? ? ? ? ? ? newFile.mkdirs();
? ? ? ? ? ? ? ? ? ? copyLocalResourcesFileToTemp(fileRoot + resource.getFilename() ?+ "/", regExpStr, tempParent + "/" + resource.getFilename());
? ? ? ? ? ? ? ? } else {
? ? ? ? ? ? ? ? ? ? if (!newFile.getParentFile().exists()) {
? ? ? ? ? ? ? ? ? ? ? ? newFile.getParentFile().mkdirs();
? ? ? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? ? ? org.apache.commons.io.FileUtils.copyInputStreamToFile(stream, newFile);
? ? ? ? ? ? ? ? }
? ? ? ? ? ? }
? ? ? ? } catch (Exception e) {
? ? ? ? ? ? log.error("failed to copy local source template", e);
? ? ? ? }
? ? }4.2.3、復(fù)制jar包里的資源文件
/**
* 復(fù)制jar包中的資源文件到指定目錄
* @param path jar包所在路徑
* @param tempPath 保存目錄
* @param filePrefix 需要進(jìn)行復(fù)制的資源文件目錄:以BOOT-INF/classes/開頭
*/
public static void copyJarResourcesFileToTemp(URI path, String tempPath, String filePrefix) {
try {
List<Map.Entry<ZipEntry, InputStream>> collect =
readJarFile(new JarFile(path.getPath()), filePrefix).collect(Collectors.toList());
for (Map.Entry<ZipEntry, InputStream> entry : collect) {
// 文件相對(duì)路徑
String key = entry.getKey().getName();
// 文件流
InputStream stream = entry.getValue();
File newFile = new File(tempPath + key.replaceAll("BOOT-INF/classes", ""));
if (!newFile.getParentFile().exists()) {
newFile.getParentFile().mkdirs();
}
org.apache.commons.io.FileUtils.copyInputStreamToFile(stream, newFile);
}
} catch (IOException e) {
log.error("failed to copy jar source template", e);
}
}@SneakyThrows
public static Stream<Map.Entry<ZipEntry, InputStream>> readJarFile(JarFile jarFile, String prefix) {
Stream<Map.Entry<ZipEntry, InputStream>> readingStream =
jarFile.stream().filter(entry -> !entry.isDirectory() && entry.getName().startsWith(prefix))
.map(entry -> {
try {
return new AbstractMap.SimpleEntry<>(entry, jarFile.getInputStream(entry));
} catch (IOException e) {
return new AbstractMap.SimpleEntry<>(entry, null);
}
});
return readingStream.onClose(() -> {
try {
jarFile.close();
} catch (IOException e) {
log.error("failed to close jarFile", e);
}
});
}以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
mybatis-plus 如何判斷參數(shù)是否為空并作為查詢條件
這篇文章主要介紹了mybatis-plus 如何判斷參數(shù)是否為空并作為查詢條件,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-03-03
Spring注解@EnableWebMvc使用的坑點(diǎn)及解析
這篇文章主要介紹了Spring注解@EnableWebMvc使用的坑點(diǎn)及解析,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-09-09
詳解Spring ApplicationContext加載過(guò)程
這篇文章主要介紹了Spring ApplicationContext加載過(guò)程的相關(guān)資料,幫助大家更好的理解和學(xué)習(xí)使用spring框架,感興趣的朋友可以了解下2021-03-03
基于Java的界面開發(fā)詳細(xì)步驟(用戶注冊(cè)登錄)
通過(guò)一段時(shí)間Java Web的學(xué)習(xí),寫一個(gè)簡(jiǎn)單的注冊(cè)登陸界面來(lái)做個(gè)總結(jié),這篇文章主要給大家介紹了基于Java的界面開發(fā)(用戶注冊(cè)登錄)的相關(guān)資料,文中通過(guò)代碼介紹的非常詳細(xì),需要的朋友可以參考下2024-01-01
java把excel內(nèi)容上傳到mysql實(shí)例代碼
這篇文章主要介紹了java把excel內(nèi)容上傳到mysql實(shí)例代碼,具有一定借鑒價(jià)值,需要的朋友可以參考下2018-01-01
SpringBoot整合Security實(shí)現(xiàn)權(quán)限控制框架(案例詳解)
Spring Security是一個(gè)能夠?yàn)榛赟pring的企業(yè)應(yīng)用系統(tǒng)提供聲明式的安全訪問(wèn)控制解決方案的安全框,是一個(gè)重量級(jí)的安全管理框架,本文給大家介紹的非常詳細(xì),需要的朋友參考下吧2021-08-08
Spring中的注解之@Override和@Autowired
看別人寫的代碼,經(jīng)常會(huì)用到 @Override 和 @Autowired 這兩個(gè)注解.這邊總結(jié)一下這兩個(gè)注解的作用,對(duì)正在學(xué)習(xí)java的小伙伴們有很好地幫助,需要的朋友可以參考下2021-05-05
Java隊(duì)列篇之實(shí)現(xiàn)數(shù)組模擬隊(duì)列及可復(fù)用環(huán)形隊(duì)列詳解
像棧一樣,隊(duì)列(queue)也是一種線性表,它的特性是先進(jìn)先出,插入在一端,刪除在另一端。就像排隊(duì)一樣,剛來(lái)的人入隊(duì)(push)要排在隊(duì)尾(rear),每次出隊(duì)(pop)的都是隊(duì)首(front)的人2021-10-10

