当前位置:网站首页>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");
边栏推荐
猜你喜欢

.NET performance optimization - you should set initial size for collection types

Tencent YunMeng every jie: I experienced by cloud native authors efficiency best practices case

Fiddle设置接口数据用指定工具查看;Sublime Text设置json数据格式化转换

HCIP--路由策略实验

DataGrip 安装教程 详细版

TodoList案例

奥特学园ROS笔记--7(289-325节)

汉源高科千兆4光4电工业级网管型智能环网冗余以太网交换机防浪涌防雷导轨式安装

56.【全局变量和局部变量专题】

交 叉 数 组
随机推荐
DataGrip 安装教程 详细版
GNN教程:图神经网络基础知识!
第七章 噪声
The time series database has been developed for 5 years. What problem does it need to solve?
一款免费的容器安全 SaaS 平台使用记录
线程安全(上)
【手撕AHB-APB Bridge】~ AMBA总线 之 APB
信息系统项目管理师必背核心考点(五十八)变更管理的主要角色
9,共模抑制比一-不受输入信号中共模波动的影响。【如何分析共模CM抑制比。】
如何成为一名正义黑客?你应该学习什么?
信息学奥赛一本通(1258:【例9.2】数字金字塔)
Implement fashion_minst clothing image classification
Solve the docker mysql can't write Chinese
pytorch的tensor创建和操作记录
李沐动手学深度学习V2-BERT预训练和代码实现
基于 flex 布局实现的三栏布局
unittest自动化测试框架总结
Fiddle设置接口数据用指定工具查看;Sublime Text设置json数据格式化转换
APP自动化uiautomator2获取toast
封装和包、访问修饰权限