当前位置:网站首页>Jar包启动通过ClassPathResource获取不到文件路径问题
Jar包启动通过ClassPathResource获取不到文件路径问题
2022-08-02 20:26:00 【DanceDonkey】
项目目录结构

maven项目resources目录也是会被编译到classpath下的。
ClassPathResource resource = new ClassPathResource("/map/map.properties");
InputStream inputStream = resource.getInputStream();
System.out.println("inputStream.available() = " + inputStream.available());
System.out.println("resource.getFile().getAbsolutePath() = " + resource.getFile().getAbsolutePath());
如果是使用idea进行本地开发时,是可以获取到classpath下的资源的路径的,因为是读取的磁盘上的真正的那个文件。

但是如果将项目打包成一个jar包后,再获取map.properties是获取不到的,对于操作系统来说最多只能读取到jar包,而不能再继续读取jar包里面的文件了,如果继续读取,只能交给jvm去读了,此时能读取到二进制流,而不能获取到路径。可通过以下几种方式获取classpath下的资源。
ClassPathResource classPathResource = new ClassPathResource("/map/map.properties");
InputStream cis = classPathResource.getInputStream();
//获取classpath下第一个/map/map.properties,这个根据jar包的加载先后顺序有关
InputStream ris = ClassPathResource.class.getClassLoader().getResourceAsStream("/map/map.properties");
//这个是获取classpath下所有的map/map.properties,在jvm运行时,所有jar都相当于是一个classpath
Enumeration<URL> resources = ClassPathResource.class.getClassLoader().getResources("/map/map.properties");
边栏推荐
猜你喜欢

Flutter 常见异常分析

信息学奥赛一本通(1259:【例9.3】求最长不下降序列)

Li Mu hands-on deep learning V2-BERT pre-training and code implementation

Use the TCP protocol, we won't lost package?

"Weekly Translate Go" This time we have something different!-- "How to Code in Go" series launched

LM小型可编程控制器软件(基于CoDeSys)笔记二十五:plc的数据存储区(数字量输入通道部分)

iframe------------frame-

模板的进阶

Day12 接口和协议

56.【全局变量和局部变量专题】
随机推荐
你所不知道的C#中的细节
Implement fashion_minst clothing image classification
Geoip2 - golang golang source code analysis
ALV concept explanation
golang 源码分析:juju/ratelimit
一款免费的容器安全 SaaS 平台使用记录
J9 Digital Currency Theory: Identifying Web3's New Scarcity: Open Source Developers
【21天学习挑战赛】冒泡排序与插入排序
LeetCode 622 设计循环队列[数组 队列] HERODING的LeetCode之路
【手撕AHB-APB Bridge】~ AMBA总线 之 APB
DataGrip 安装教程 详细版
Wintun:一款惊艳的 WireGuard 虚拟网卡接口驱动
OP-5,输入/输出信号范围-一信号处理能力
EasyExcel dynamic parsing and save table columns
A brief discussion on the transformation of .NET legacy applications
供电系统电气图
HCIP--路由策略实验
Details in C# you don't know
Bena's life cycle
李沐动手学深度学习V2-bert和代码实现