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