当前位置:网站首页>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");
边栏推荐
- 如何使用windbg查看C#某个线程的栈大小 ?
- 一次线上事故,我顿悟了异步的精髓
- 「 每日一练,快乐水题 」1374. 生成每种字符都是奇数个的字符串
- Golang source code analysis: time/rate
- Informatics Olympiad All-in-One (1257: Knight Moves)
- 基于“无依赖绝对定位”实现的圣杯三栏布局
- golang 源码分析:uber-go/ratelimit
- "Weekly Translate Go" This time we have something different!-- "How to Code in Go" series launched
- Li Mu hands-on learning deep learning V2-bert and code implementation
- 并发与并行
猜你喜欢
随机推荐
MSTP与STP
Async的线程池使用的哪个?
The software testing process specification is what?Specific what to do?
EasyExcel dynamic parsing and save table columns
arm64麒麟安装paddlehub(国产化)
Wiring diagrams of switches, motors, circuit breakers, thermocouples, and meters
李沐动手学深度学习V2-bert预训练数据集和代码实现
引用类型 ,值类型 ,小坑。
Day35 LeetCode
信息系统项目管理师必背核心考点(五十八)变更管理的主要角色
基于“无依赖绝对定位”实现的圣杯三栏布局
A brief discussion on the transformation of .NET legacy applications
J9 Digital Currency Theory: Identifying Web3's New Scarcity: Open Source Developers
"Weekly Translate Go" This time we have something different!-- "How to Code in Go" series launched
ABAP grammar small review
WPF development through practical 】 【 automatic production management platform
李沐动手学深度学习V2-bert和代码实现
谷歌竞价机器学习如何去理解?
C# Barrier类
数据库分析与优化









