java 读取静态资源文件_SpringBoot读取静态资源文件

本文介绍了如何在SpringBoot中使用ClassPathResource读取静态资源文件,如XML等,强调了在项目打包成Jar后如何正确获取资源文件的输入流,以避免无法找到资源的问题。
摘要由CSDN通过智能技术生成

ClassPathResource resource = new ClassPathResource(publicKeyCer);

File file = null;

try {

file = resource.getFile();

} catch (IOException e) {

e.printStackTrace();

}

InputStream inStream = new FileInputStream( file.getPath());

一、需求场景

有时候我们需要在项目中使用一些静态资源文件,比如城市信息文件 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)));

1

2

3

ClassPathResource 类的注释如下:

Resource implementation for class path resources. Uses either a given ClassLoader or a given Class

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值