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
透過相對路徑讀取:
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包中資源進行遍歷。
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包資源目錄
以複製resource資源目錄為例,分別對本地和jar包中的資源進行複製。
如下所示:
我要複製resource資源目錄下的template資料夾下的所有內容;
然後儲存到C:/Users/ASUS/Desktop/ savePath資料夾下。
4.2.1、環境判斷
public static void main(String[] args) throws URISyntaxException { // Test为当前类名 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运行时,进行资源复制 copyLocalResourcesFileToTemp(sourceDir + "/", "*", tempPath + "/" + sourceDir); } else { // 获取jar包所在路径 String jarPath = uri.toString(); uri = URI.create(jarPath.substring(jarPath.indexOf("file:"),jarPath.indexOf(".jar") + 4)); // 打成jar包后,进行资源复制 Test.copyJarResourcesFileToTemp(uri, tempPath, "BOOT-INF/classes/" + sourceDir); } }
4.2.2、複製本機專案的資源檔案
/** * 复制本地资源文件到指定目录 * @param fileRoot 需要复制的资源目录文件夹 * @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、複製jar包裡的資源檔
/** * 复制jar包中的资源文件到指定目录 * @param path jar包所在路径 * @param tempPath 保存目录 * @param filePrefix 需要进行复制的资源文件目录:以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); } }); }
以上是如何在Java中讀取JAR包中的資源檔案?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

本文討論了使用Maven和Gradle進行Java項目管理,構建自動化和依賴性解決方案,以比較其方法和優化策略。

本文使用Maven和Gradle之類的工具討論了具有適當的版本控制和依賴關係管理的自定義Java庫(JAR文件)的創建和使用。

本文討論了使用咖啡因和Guava緩存在Java中實施多層緩存以提高應用程序性能。它涵蓋設置,集成和績效優勢,以及配置和驅逐政策管理最佳PRA

本文討論了使用JPA進行對象相關映射,並具有高級功能,例如緩存和懶惰加載。它涵蓋了設置,實體映射和優化性能的最佳實踐,同時突出潛在的陷阱。[159個字符]

Java的類上載涉及使用帶有引導,擴展程序和應用程序類負載器的分層系統加載,鏈接和初始化類。父代授權模型確保首先加載核心類別,從而影響自定義類LOA


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

AI Hentai Generator
免費產生 AI 無盡。

熱門文章

熱工具

MantisBT
Mantis是一個易於部署的基於Web的缺陷追蹤工具,用於幫助產品缺陷追蹤。它需要PHP、MySQL和一個Web伺服器。請查看我們的演示和託管服務。

記事本++7.3.1
好用且免費的程式碼編輯器

MinGW - Minimalist GNU for Windows
這個專案正在遷移到osdn.net/projects/mingw的過程中,你可以繼續在那裡關注我們。 MinGW:GNU編譯器集合(GCC)的本機Windows移植版本,可自由分發的導入函式庫和用於建置本機Windows應用程式的頭檔;包括對MSVC執行時間的擴展,以支援C99功能。 MinGW的所有軟體都可以在64位元Windows平台上運作。

PhpStorm Mac 版本
最新(2018.2.1 )專業的PHP整合開發工具

SublimeText3漢化版
中文版,非常好用