spingboot打成jar之后,读取不到相对路径。eg.Resource下文件
在本地项目启动的时候,可以使用AttachmentUtil.class.getClassLoader().getResource(path);读取到文件。
但是项目打成jar之后,读取不到文件。会报错java.io.FileNotFoundException
主要原因是springboot内置tomcat,打包后是一个jar包,因此通过文件读取获取流的方式行不通,因为无法直接读取压缩包中的文件,读取只能通过流的方式读取。
ClassPathResource classPathResource = new ClassPathResource(path);
InputStream inputStream =classPathResource.getInputStream();
1.当你要将文件内容读取成字符串时
/**
* 读取指定路径的模板文件为String
*/
public String getTemplateHtmlString(String path) throws IOException {
ClassPathResource classPathResource = new ClassPathResource(path);
InputStream inputStream =classPathResource.getInputStream();
if (inputStream == null) {