最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Java如何讀取jar包中的resource資源文件

 更新時間:2022年08月17日 17:18:26   作者:零點冰.  
這篇文章主要介紹了Java如何讀取jar包中的resource資源文件,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教

1、需求       

在Java項目中,需要讀取resource資源目錄下的文件,以及遍歷指定資源目錄下的所有文件,并且在讀取文件時保留文件相對路徑。

2、問題       

在IDEA中運行時,可以獲取并遍歷指定資源,但是將Java項目打成jar包運行后,就無法獲取resource資源目錄下的文件。

3、IDEA讀取resource資源       

編譯后,資源文件放在target目錄下,每一個資源文件實實在在存在于磁盤中。

3.1、方法1       

直接通過絕對路徑讀取,如果file是目錄,也可以通過listFiles遞歸遍歷目錄下文件:

String absolutePath = "資源文件絕對路徑";
File file = new File(absolutePath);
if (file.isDirectory()) {
? ? File[] children = file.listFiles();
}

3.2、方法2       

通過相對路徑讀?。?/p>

String path = "template"; ? ?//相對resource路徑
File file = ResourceUtils.getFile(ResourceUtils.CLASSPATH_URL_PREFIX + path);
if (file.isDirectory()) {
? ? File[] children = file.listFiles();
}

4、打成jar包后讀取resource資源       

以上兩種方法無法讀取jar包中的資源文件。

       

打成jar包后,jar包是一個單獨的文件而不是文件夾,所以通過文件路徑是無法定位到資源文件的。此時,可通過類加載器讀取jar包中的資源文件。

4.1、讀取jar包中的資源文件       

這種方式只能讀取jar包中單個文件,因為讀取出來的是InputStream流,無法保留文件相對于resource的路徑,所以無法對jar包中資源進(jìn)行遍歷。

String path = "/resource相對路徑";
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資源目錄為例,分別對本地和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運行時,進(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ù)制本地項目的資源文件

/**
? ? ?* 復(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為文件夾時,會報異常,這里直接忽略這個異常
? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? 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) {
                // 文件相對路徑
                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);
            }
        });
    }

以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。 

相關(guān)文章

  • 注意Java中?new?BigDecimal(double?val)?的使用

    注意Java中?new?BigDecimal(double?val)?的使用

    這篇文章主要介紹了注意Java中?new?BigDecimal(double?val)?的使用,文章圍繞主題展開詳細(xì)的內(nèi)容介紹,具有一定的參考價值,需要的朋友可以參考一下
    2022-07-07
  • 零基礎(chǔ)如何系統(tǒng)的學(xué)習(xí)Java

    零基礎(chǔ)如何系統(tǒng)的學(xué)習(xí)Java

    這篇文章主要介紹了零基礎(chǔ)如何系統(tǒng)的學(xué)習(xí)Java,很多朋友糾結(jié)這個問題,教材書不知道從何學(xué)起,今天小編給大家分享一篇教程幫助到家梳理這方面的知識
    2020-07-07
  • SpringBoot數(shù)據(jù)庫恢復(fù)的兩種方法mysqldump和mysqlbinlog

    SpringBoot數(shù)據(jù)庫恢復(fù)的兩種方法mysqldump和mysqlbinlog

    binlog用來實現(xiàn)主從復(fù)制,也常用來誤刪數(shù)據(jù)庫找回丟失的記錄,本文主要介紹了SpringBoot數(shù)據(jù)庫恢復(fù)的兩種方法mysqldump和mysqlbinlog,具有一定的參考價值,感興趣的可以了解一下
    2024-01-01
  • Spring Cloud 的 Hystrix.功能及實踐詳解

    Spring Cloud 的 Hystrix.功能及實踐詳解

    這篇文章主要介紹了Spring Cloud 的 Hystrix.功能及實踐詳解,Hystrix 具備服務(wù)降級、服務(wù)熔斷、線程和信號隔離、請求緩存、請求合并以及服務(wù)監(jiān)控等強(qiáng)大功能,需要的朋友可以參考下
    2019-07-07
  • Reactor3 Map與FlatMap的區(qū)別示例詳解

    Reactor3 Map與FlatMap的區(qū)別示例詳解

    這篇文章主要為大家介紹了Reactor3 Map與FlatMap的區(qū)別示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2023-08-08
  • idea上提交項目到gitee 最后出現(xiàn) Push rejected的問題處理方法

    idea上提交項目到gitee 最后出現(xiàn) Push rejected的問題處理方法

    這篇文章主要介紹了idea上面提交項目到gitee 最后出現(xiàn) Push rejected的問題處理方法,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定參考借鑒價值,需要的朋友可以參考下
    2020-09-09
  • java -jar后臺啟動的四種方式小結(jié)

    java -jar后臺啟動的四種方式小結(jié)

    這篇文章主要介紹了java -jar后臺啟動的四種方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2023-09-09
  • ConcurrentHashMap是如何實現(xiàn)線程安全的你知道嗎

    ConcurrentHashMap是如何實現(xiàn)線程安全的你知道嗎

    這篇文章主要介紹了ConcurrentHashMap是如何實現(xiàn)線程安全的你知道嗎,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-10-10
  • MyBatis-Plus updateById不更新null值的方法解決

    MyBatis-Plus updateById不更新null值的方法解決

    用Mybatis-Plus的updateById()來更新數(shù)據(jù)時,無法將字段設(shè)置為null值,更新后數(shù)據(jù)還是原來的值,本文就來詳細(xì)的介紹一下解決方法,具有一定的參考價值,感興趣的可以了解一下
    2023-08-08
  • Hadoop源碼分析三啟動及腳本剖析

    Hadoop源碼分析三啟動及腳本剖析

    本篇是Hadoop源碼分析系列文章第三篇,主要介紹Hadoop啟動以及腳本的剖析,后續(xù)本系列文章會持續(xù)更新,有需要的朋友可以借鑒參考下
    2021-09-09

最新評論

建宁县| 娱乐| 南和县| 晋江市| 崇左市| 海兴县| 潜山县| 广宗县| 淅川县| 正阳县| 正镶白旗| 牟定县| 商都县| 门头沟区| 合水县| 罗江县| 淳安县| 星座| 诏安县| 晋江市| 嘉峪关市| 宁南县| 五原县| 集贤县| 高要市| 德清县| 兴义市| 二连浩特市| 肇源县| 静安区| 余干县| 德昌县| 东莞市| 青川县| 于都县| 宝鸡市| 秦安县| 盐亭县| 北票市| 临泉县| 荥经县|