Spring Boot 读取静态资源文件
来源:互联网 发布:剑网三捏脸数据下载 编辑:程序博客网 时间:2024/05/20 20:18
一、需求场景
有时候我们需要在项目中使用一些静态资源文件,比如城市信息文件 countries.xml
,在项目启动后读取其中的数据并初始化写进数据库中。
二、实现
静态资源文件 countries.xml
放在 src/main/resources
目录下
使用 Spring 的 ClassPathResource 来实现 :
Resource resource = new ClassPathResource("countries.xml");File file = resource.getFile();BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
ClassPathResource
类的注释如下:
Resource implementation for class path resources. Uses either a given ClassLoader or a given Class for loading resources.Supports resolution as java.io.File if the class path resource resides in the file system, but not for resources in a JAR. Always supports resolution as URL.
翻译过来就是:
类路径资源的资源实现。使用给定的ClassLoader或给定的类来加载资源。如果类路径资源驻留在文件系统中,则支持解析为 java.io.File,如果是JAR中的资源则不支持。始终支持解析为URL。
三、Jar 中资源文件
上面也提到了,如果静态资源文件在文件系统里,则支持解析为 java.io.File
,程序是能正常工作的。
到项目打包成 Jar
包放到服务器上运行就报找不到资源的错误了!
解决法案是:不获取 java.io.File
对象,而是直接获取输入流
:
Resource resource = new ClassPathResource("countries.xml");BufferedReader br = new BufferedReader(new InputStreamReader(resource.getInputStream()));
说明:构造得到 resource
对象之后直接获取其输入流 resource.getInputStream()
。
四、附录
- Spring Boot access static resources missing scr/main/resources
- Classpath resource not found when running as jar
唉唉,好水的一篇博客 ):
1 0
- Spring Boot 读取静态资源文件
- spring boot 读取本地静态资源
- (3) Spring boot静态资源文件获取
- 【Spring Boot】Spring Boot 静态资源处理
- spring-boot 加载本地静态资源文件路径配置
- spring-boot 加载本地静态资源文件路径配置
- spring-boot 加载本地静态资源文件路径配置
- spring boot 加载本地静态资源文件路径配置
- spring-boot 加载本地静态资源文件路径配置
- spring-boot 加载本地静态资源文件路径配置
- spring boot静态资源文件的访问以及自定义
- Spring Boot 静态资源处理
- Spring Boot 静态资源处理
- spring boot 静态资源处理
- Spring Boot 静态资源处理
- Spring Boot 静态资源处理
- Spring Boot 静态资源处理
- Spring Boot 静态资源处理
- spring 源码-循环依赖
- python3.5安装paramiko模块
- H
- 设计模式
- 字符串匹配算法
- Spring Boot 读取静态资源文件
- c语言题目集合
- ps之解决eps图片不能保存为png格式问题
- rational rose逆向工程导入JAVA项目
- react-native无法显示图片的解决办法
- 数据链路层差错检测:CRC(循环冗余检验)
- 归并排序 51nod 1019 逆序数
- float属性与块级元素、内联元素
- [UVA 12298 Super Poker II]FFT/NTT