如何读取运行jar中引用jar中的文件

1.问题发现

       项目中有个common包资源文件,然后springboot项目引用了common,那么我们要怎么读取这个资源了。这里需要考虑三个场景,idea运行时、common jar独立运行时、springboot引用common后运行时。

2.问题解决

2.1.idea运行时

 ProtectionDomain protectionDomain = LibPaths.class.getProtectionDomain();CodeSource codeSource = protectionDomain.getCodeSource();if (codeSource != null) {String jarPath = codeSource.getLocation().getPath();jarPath = jarPath.replaceFirst("^nested:", "");if(!jarPath.endsWith(".jar")){System.out.println("idea运行时classes路径");}

2.2.common jar运行时 

public static String getUrl(){ProtectionDomain protectionDomain = LibPaths.class.getProtectionDomain();CodeSource codeSource = protectionDomain.getCodeSource();if (codeSource != null) {String jarPath = codeSource.getLocation().getPath();jarPath = jarPath.replaceFirst("^nested:", "");System.out.println("JAR 文件路径: " + jarPath);if(jarPath != null){int index = jarPath.indexOf(".jar");String destDir = jarPath;if(index != -1){destDir = new File(jarPath.substring(0, index+4)).getParent();}if(jarPath.endsWith(".jar")){copyJarCuToOut(jarPath,destDir)}else{System.out.println("idea运行时classes路径");}}
}public static void copyJarCuToOut(String jarPath,String destDir) throws IOException {File file = new File(destDir + File.separator + "test");if(!file.exists()){file.mkdirs();copyResourcesFromJar(jarPath,destDir, true);}else{System.out.println(file.getPath() + "已存在");}
}/*** 将 JAR 中指定路径下的所有文件复制到目标目录** @param jarFilePath   JAR 文件的路径* @param resourcePath  JAR 中的资源路径(例如 "resources/")* @param destDir       目标输出目录* @throws IOException  如果复制过程中出现错误*/
public static void copyResourcesFromJar(String jarFilePath, String resourcePath, String destDir) throws IOException {try (JarFile jarFile = new JarFile(jarFilePath)) {Enumeration<JarEntry> entries = jarFile.entries();while (entries.hasMoreElements()) {JarEntry entry = entries.nextElement();if (entry.getName().startsWith(resourcePath) && !entry.isDirectory() && ( entry.getName().endsWith(".cu") || entry.getName().endsWith(".cu.h"))) {// 构建目标路径Path destPath = Paths.get(destDir + File.separator + entry.getName().substring(resourcePath.length()));// 复制文件try (InputStream is = jarFile.getInputStream(entry);OutputStream os = Files.newOutputStream(destPath)) {byte[] buffer = new byte[1024];int len;while ((len = is.read(buffer)) > 0) {os.write(buffer, 0, len);}}System.out.println("已复制: " + entry.getName() + " 到 " + destPath);}}}
}

2.3.springboot jar运行时  

public static String getUrl(){ProtectionDomain protectionDomain = LibPaths.class.getProtectionDomain();CodeSource codeSource = protectionDomain.getCodeSource();if (codeSource != null) {String jarPath = codeSource.getLocation().getPath();jarPath = jarPath.replaceFirst("^nested:", "");System.out.println("JAR 文件路径: " + jarPath);if(jarPath != null){int index = jarPath.indexOf(".jar");String destDir = jarPath;if(index != -1){destDir = new File(jarPath.substring(0, index+4)).getParent();}if(jarPath.endsWith(".jar")){copyJarCuToOut(jarPath,destDir)}else{System.out.println("idea运行时classes路径");}}
}public static void copyJarCuToOut(String jarPath,String destDir) throws IOException {File file = new File(destDir + File.separator + "test");if(!file.exists()){file.mkdirs();copyResourcesFromMultipleJar(jarPath,destDir, true);}else{System.out.println(file.getPath() + "已存在");}
}/*** 将 JAR 中指定路径下的所有文件复制到目标目录** @param jarFilePath   JAR 文件的路径* @param resourcePath  JAR 中的资源路径(例如 "resources/")* @param destDir       目标输出目录* @throws IOException  如果复制过程中出现错误*/
public static void copyResourcesFromMultipleJar(String jarFilePath, String resourcePath, String destDir) throws IOException {// 1. 分离路径部分String[] parts = jarFilePath.split("/!");if (parts.length < 2) {throw new IllegalArgumentException("无效的嵌套 JAR 路径格式");}// 2. 解析外层 JAR 路径(去掉开头的 / 和 !/)String outerJarPath = parts[0];String innerJarEntry = parts[1].replace("!/", "");System.out.println("###################" + outerJarPath);// 3. 打开外层 JARtry (JarFile outerJar = new JarFile(outerJarPath)) {// 4. 获取内层 JAR 的 EntryJarEntry innerEntry = outerJar.getJarEntry(innerJarEntry);if (innerEntry == null) {throw new FileNotFoundException("内层 JAR 不存在: " + innerJarEntry);}System.out.println("innerJarEntry###################" + innerJarEntry);try (InputStream innerIs = outerJar.getInputStream(innerEntry); JarInputStream innerJar = new JarInputStream(innerIs)) {JarEntry entry;while ((entry = innerJar.getNextJarEntry()) != null) {if (entry.getName().startsWith(resourcePath) && !entry.isDirectory()) {// 构建目标路径Path destPath = Paths.get(destDir + File.separator + entry.getName().substring(resourcePath.length()));// 复制文件try (OutputStream os = Files.newOutputStream(destPath)) {byte[] buffer = new byte[1024];int len;while ((len = innerJar.read(buffer)) > 0) {os.write(buffer, 0, len);}}System.out.println("已复制: " + entry.getName() + " 到 " + destPath);}}}}}

2.4.完整代码

package com.omega.common.lib;import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.CodeSource;
import java.security.ProtectionDomain;
import java.util.Enumeration;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.jar.JarInputStream;public class LibPaths {static {try {// 获取 ProtectionDomain 和 CodeSourceProtectionDomain protectionDomain = LibPaths.class.getProtectionDomain();CodeSource codeSource = protectionDomain.getCodeSource();if (codeSource != null) {String jarPath = codeSource.getLocation().getPath();jarPath = jarPath.replaceFirst("^nested:", "");System.out.println("JAR 文件路径: " + jarPath);if(jarPath != null){int index = jarPath.indexOf(".jar");String destDir = jarPath;if(index != -1){destDir = new File(jarPath.substring(0, index+4)).getParent();}if(jarPath.endsWith(".jar")){copyJarCuToOut(jarPath,destDir, false);}else if(jarPath.endsWith(".jar!/")){copyJarCuToOut(jarPath,destDir, true);}LIB_PATH = destDir + File.separator + "test";}else{System.out.println("JAR 文件路径为空");}} else {System.out.println("无法获取 JAR 路径(可能来自系统类加载器)");}} catch (IOException e) {e.printStackTrace();}}public static void copyJarCuToOut(String jarPath,String destDir, boolean multiple) throws IOException {File file = new File(destDir + File.separator + "test");if(!file.exists()){file.mkdirs();if(multiple){copyResourcesFromMultipleJar(jarPath, "test", file.getPath());}else{copyResourcesFromJar(jarPath, "test", file.getPath());}}else{System.out.println(file.getPath() + "已存在");}}/*** 将 JAR 中指定路径下的所有文件复制到目标目录** @param jarFilePath   JAR 文件的路径* @param resourcePath  JAR 中的资源路径(例如 "resources/")* @param destDir       目标输出目录* @throws IOException  如果复制过程中出现错误*/public static void copyResourcesFromJar(String jarFilePath, String resourcePath, String destDir) throws IOException {try (JarFile jarFile = new JarFile(jarFilePath)) {Enumeration<JarEntry> entries = jarFile.entries();while (entries.hasMoreElements()) {JarEntry entry = entries.nextElement();if (entry.getName().startsWith(resourcePath) && !entry.isDirectory() && ( entry.getName().endsWith(".cu") || entry.getName().endsWith(".cu.h"))) {// 构建目标路径Path destPath = Paths.get(destDir + File.separator + entry.getName().substring(resourcePath.length()));// 复制文件try (InputStream is = jarFile.getInputStream(entry);OutputStream os = Files.newOutputStream(destPath)) {byte[] buffer = new byte[1024];int len;while ((len = is.read(buffer)) > 0) {os.write(buffer, 0, len);}}System.out.println("已复制: " + entry.getName() + " 到 " + destPath);}}}}/*** 将 JAR 中指定路径下的所有文件复制到目标目录** @param jarFilePath   JAR 文件的路径* @param resourcePath  JAR 中的资源路径(例如 "resources/")* @param destDir       目标输出目录* @throws IOException  如果复制过程中出现错误*/public static void copyResourcesFromMultipleJar(String jarFilePath, String resourcePath, String destDir) throws IOException {// 1. 分离路径部分String[] parts = jarFilePath.split("/!");if (parts.length < 2) {throw new IllegalArgumentException("无效的嵌套 JAR 路径格式");}// 2. 解析外层 JAR 路径(去掉开头的 / 和 !/)String outerJarPath = parts[0];String innerJarEntry = parts[1].replace("!/", "");System.out.println("###################" + outerJarPath);// 3. 打开外层 JARtry (JarFile outerJar = new JarFile(outerJarPath)) {// 4. 获取内层 JAR 的 EntryJarEntry innerEntry = outerJar.getJarEntry(innerJarEntry);if (innerEntry == null) {throw new FileNotFoundException("内层 JAR 不存在: " + innerJarEntry);}System.out.println("innerJarEntry###################" + innerJarEntry);try (InputStream innerIs = outerJar.getInputStream(innerEntry); JarInputStream innerJar = new JarInputStream(innerIs)) {JarEntry entry;while ((entry = innerJar.getNextJarEntry()) != null) {if (entry.getName().startsWith(resourcePath) && !entry.isDirectory()) {// 构建目标路径Path destPath = Paths.get(destDir + File.separator + entry.getName().substring(resourcePath.length()));// 复制文件try (OutputStream os = Files.newOutputStream(destPath)) {byte[] buffer = new byte[1024];int len;while ((len = innerJar.read(buffer)) > 0) {os.write(buffer, 0, len);}}System.out.println("已复制: " + entry.getName() + " 到 " + destPath);}}}}}}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如若转载,请注明出处:http://www.pswp.cn/news/912591.shtml
繁体地址,请注明出处:http://hk.pswp.cn/news/912591.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

【学习方法】框架质疑学习法:破解专业学习的“知识厚度”困境

今天博主给大家分享一个&#xff0c;我自己发明了一个比较高效的学习方法,名叫“框架质疑学习法” 本文提出的框架质疑学习法&#xff08;Framework Questioning Learning Method&#xff09;为本文作者&#xff0c;也就是我&#xff0c;董翔首次提出。 在软件专业的学习中&a…

spring-ai 1.0.0 学习(十七)——MCP Client

之前学过了工具调用&#xff08;spring-ai 1.0.0 学习&#xff08;十二&#xff09;——工具调用_springai 1.0 如何判断调用哪一个tool工具-CSDN博客&#xff09;&#xff0c;今天来看一下MCP MCP是什么 MCP全称是模型上下文协议&#xff0c;有点绕&#xff0c;通俗点理解&a…

Git 运行.sh文件

1.在项目文件中右击 Open Git Bash here 显示&#xff08;base&#xff09;环境 2.激活conda环境 3.复制.sh文件的相对路径 4.将路径复制到git终端 先输入sh和空格&#xff0c;然后右击后选paste&#xff0c;不要直接ctrl v 5.开始运行

MySQL InnoDB 引擎中的聚簇索引和非聚簇索引有什么区别?

MySQL InnoDB 引擎中的聚簇索引和非聚簇索引有什么区别&#xff1f; 主要解答详细解答1. **聚簇索引&#xff08;Clustered Index&#xff09;**2. **非聚簇索引&#xff08;Non-Clustered Index / Secondary Index&#xff09;**3. **对比总结**4. **流程图&#xff08;查询过…

[2025CVPR]DE-GANs:一种高效的生成对抗网络

目录 引言:数据高效GAN的困境 核心原理:动态质量筛选机制 1. 判别器拒绝采样(DRS)的再思考 2. 质量感知动态拒绝公式 (1)质量感知阶段 (2)动态拒绝阶段 模型架构:轻量化设计 技术突破:三大创新点 1. 首创训练阶段DRS 2. 动态拒绝机制 3. 质量重加权策略 …

[面试] 手写题-数组转树

示例数据&#xff1a; const arr [{ id: 1, parentId: null, name: Root },{ id: 2, parentId: 1, name: Child 1 },{ id: 3, parentId: 1, name: Child 2 },{ id: 4, parentId: 2, name: Grandchild 1 }, ]目标生成&#xff1a; const tree [{id: 1,name: Root,children: …

CertiK《Hack3d:2025年第二季度及上半年Web3.0安全报告》(附报告全文链接)

CertiK《Hack3d&#xff1a;2025年第二季度及上半年Web3.0安全报告》现已发布&#xff0c;报告显示&#xff1a;仅2025年上半年&#xff0c;因安全事件导致的损失接近25亿美元&#xff1b;截至目前&#xff0c;总损失已超过去年全年水平。整体来看&#xff0c;Web3.0安全形势依…

反向传播 梯度消失

反向传播 backpropagation 反向传播&#xff08;Backpropagation&#xff09; 是神经网络训练中的一种核心算法&#xff0c;用于通过计算误差并将其传播回网络&#xff0c;从而更新神经网络的参数。通过反向传播&#xff0c;网络能够在每次迭代中逐步调整其参数&#xff08;例…

京东外卖服务商加入方案对比!选择本地生活服务商系统的优势,到底在哪?

自入局之日起&#xff0c;京东外卖似乎就一直热衷于给人惊喜&#xff1a; 先是在上线时规定了“2025年5月1日前入驻的商家&#xff0c;全年免佣金”和“仅限品质堂食商家入驻”&#xff1b; 再是宣布了要为外卖骑手缴纳五险一金&#xff0c;并承担其中的所有成本&#xff1b;…

【RTSP从零实践】4、使用RTP协议封装并传输AAC

&#x1f601;博客主页&#x1f601;&#xff1a;&#x1f680;https://blog.csdn.net/wkd_007&#x1f680; &#x1f911;博客内容&#x1f911;&#xff1a;&#x1f36d;嵌入式开发、Linux、C语言、C、数据结构、音视频&#x1f36d; &#x1f923;本文内容&#x1f923;&a…

Bootstrap 安装使用教程

一、Bootstrap 简介 Bootstrap 是一个开源的前端框架&#xff0c;由 Twitter 开发&#xff0c;旨在快速开发响应式、移动优先的 Web 页面。它包含 HTML、CSS 和 JavaScript 组件&#xff0c;如按钮、导航栏、表单等。 二、Bootstrap 安装方式 2.1 使用 CDN&#xff08;推荐入…

Java学习第二部分——基础语法

目录 一.数据类型 &#xff08;一&#xff09;数值类型&#xff08;用于存储数字&#xff0c;包括整数和浮点数&#xff09; 1. **整数类型** 2. **浮点类型** &#xff08;二&#xff09;非数值类型&#xff08;非数值类型用于存储非数字数据&#xff09; 1. **char** 2…

Redis分布式锁核心原理源码

文章目录 概述一、Redis实现分布式锁1.1、第一版1.2、第二版1.3、第三版1.3、第四版 二、Redisson实现分布式锁核心源码分析2.1、加锁核心源码2.2、锁续期核心源码2.3、重试机制核心源码2.4、解锁核心源码 总结 概述 传统的单机锁&#xff08;Synchronized&#xff0c;Reentran…

关于vue2使用elform的rules校验

在使用vue2开发项目的时候使用element组件的el-form大多数情况都需要用到必填项校验 举个栗子&#xff1a; <el-form :model"ruleForm" :rules"rules" ref"ruleForm" label-width"100px" class"demo-ruleForm"><e…

langchain从入门到精通(二十六)——RAG优化策略(四)问题分解策略提升负责问题检索准确率

1. LangChain 少量示例提示模板 在与 LLM 的对话中&#xff0c;提供少量的示例被称为 少量示例&#xff0c;这是一种简单但强大的指导生成的方式&#xff0c;在某些情况下可以显著提高模型性能&#xff08;与之对应的是零样本&#xff09;&#xff0c;少量示例可以降低 Prompt…

Nuxt.js基础(Tailwind基础)

​​1. 按钮组件实现​​ ​​传统 CSS <!-- HTML --> <button class"btn-primary">提交</button><!-- CSS --> <style>.btn-primary {background-color: #3490dc;padding: 0.5rem 1rem;border-radius: 0.25rem;color: white;transi…

[C语言]存储结构详解

C语言存储结构总结 在C语言中&#xff0c;数据根据其类型和声明方式被存储在不同的内存区域。以下是各类数据存储位置的详细总结&#xff1a; 内存五大分区 存储区存储内容生命周期特点代码区(.text)程序代码(机器指令)整个程序运行期只读常量区(.rodata)字符串常量、const全…

【实战】 容器中Spring boot项目 Graphics2D 画图中文乱码解决方案

场景 架构&#xff1a;spring boot 容器技术&#xff1a;docker 服务器&#xff1a;阿里云 开发环境&#xff1a;windows10 IDEA 一、问题 服务器中出现Graphics2D 画图中文乱码 本地环境运行正常 二、原因 spring boot 容器中没有安装中文字体 三、解决方案 安装字体即可 …

深入浅出:Vue2 数据劫持原理剖析

目录 一、什么是数据劫持&#xff1f; 二、核心 API&#xff1a;Object.defineProperty 三、Vue2 中的数据劫持实现 1. 对象属性的劫持 2. 嵌套对象的处理 3. 数组的特殊处理 四、结合依赖收集的完整流程 五、数据劫持的局限性 六、Vue3 的改进方案 总结 一、什么是数…

数据湖 vs 数据仓库:数据界的“自来水厂”与“瓶装水厂”?

数据湖 vs 数据仓库&#xff1a;数据界的“自来水厂”与“瓶装水厂”&#xff1f; 说起“数据湖”和“数据仓库”&#xff0c;很多刚入行的朋友都会觉得&#xff1a; “听起来好高大上啊&#xff01;但到底有啥区别啊&#xff1f;是湖更大还是仓库更高端&#xff1f;” 我得说…