springboot项目需要获取资源目录下的json文件,本地使用getClassLoader().getResource()获取可以,但是部署到线上后,获取到文件路径是file:/tmp/sop.jar!/BOOT-INF/classes!/ueditor-config.json,解决方案使用ClassPathResource类
getClassLoader().getResource()
private String configPath = this.getClass().getClassLoader().getResource("ueditor-config.json").getPath();
// configPath = /E:/Development/xxx/target/classes/ueditor-config.json
StringBuilder builder = new StringBuilder();
try {
InputStreamReader reader = new InputStreamReader(new FileInputStream(configPath), "UTF-8");
BufferedReader bfReader = new BufferedReader(reader);
String tmpContent = null;
while ((tmpContent = bfReader.readLine()) != null) {
builder.append(tmpContent);
}
bfReader.close();
} catch (UnsupportedEncodingException e) {
// 忽略
}
- idea 本地运行时,configPath = /E:/Development/xxx/target/classes/ueditor-config.json
- 部署到线上运行,configPath = file:/tmp/sop.jar!/BOOT-INF/classes!/ueditor-config.json
- 线上不能使用该方式
原因
Java项目部署到线上时,会将项目打包成一个jar包,jar包是一个文件,而不是文件夹,因此通过/tmp/sop.jar!/BOOT-INF/classes!/ueditor-config.json无法定位到文件。
ClassPathResource类
Resource resource = new ClassPathResource(configPath);
InputStream is = resource.getInputStream();
StringBuilder builder = new StringBuilder();
try {
InputStreamReader reader = new InputStreamReader(is, "UTF-8");
BufferedReader bfReader = new BufferedReader(reader);
String tmpContent = null;
while ((tmpContent = bfReader.readLine()) != null) {
builder.append(tmpContent);
}
bfReader.close();
} catch (UnsupportedEncodingException e) {
// 忽略
}
通过 ClassPathResource读取资源路径下的文件,可以直接获取到一个输入流,然后对流进行操作即可。