springboot jar启动 读取jar包中相对路径文件报错

时间:2024-04-06 17:04:47
jar包启动后读取相对路径文件报异常:
Caused by: java.io.FileNotFoundException: class path resource [***.***] cannot be resolved to absolute
.***.jar/BOOT-INF/classes!/***.**

采用流的方式读取即可解决

// /template/template.html是resource下面的文件
String template=readfile("/template/template.html");
//file 相对路径
public String readfile(String file){
InputStream stream = this.getClass().getResourceAsStream(file);
StringBuffer sb = new StringBuffer() ;
BufferedReader br = null ;
try {
br = new BufferedReader(new InputStreamReader(stream,"UTF-8")) ;
String s=null ;
while((s=br.readLine()) !=null){
sb.append(s) ;
}
br.close();
} catch (FileNotFoundException e) {
log.error("FileNotFoundException:"+e);
} catch (IOException e) {
log.error("IOException :"+e);
}finally {
if(br !=null){
try {
br.close();
} catch (IOException e) {
log.error("close br error:"+e);
}
}
}
return sb.toString();
}