问题描述:JAR包部署到生产环境上加载不到资源(fIle not found exeception),但本地IDEA是可以加载的。
new FileReader("classpath:template/merge_sql_template.sql");
原因:和war部署不同,resources下的文件是存在在jar包中的,仅是jar中的内部路径,在磁盘中没有真实路径。直接用File读取是访问真实路径,故访问不到。
解决:绕过创建File的方式,直接使用 this.getClass().getClassLoader().getResourceAsStream 获取内部jar文件的输入流
String mergeSqlTemplate = "";try (InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("sql/merge_sql_template.sql");) {byte[] buff = new byte[1024];int btr = 0;while ((btr = inputStream.read(buff)) != -1) {mergeSqlTemplate += new String(buff, 0, btr, "UTF-8");}} catch (IOException e) {e.printStackTrace();throw new GeneralException("模版文件解析失败");}
参考
【1】:https://blog.csdn.net/supersolon/article/details/119023255
