原创

【Java】jar启动的java程序报错FileNotFoundException

前言

做了个周报系统,用来生成周报,维护周报,遇到了模板文件找不到的问题,死活不行,下面是报错信息

java.io.FileNotFoundException: class path resource [templates/weeklyrep/content/weelyrep_2.xlsx] cannot be resolved to absolute file path because it does not reside in the file system: jar:file:/home/weekely.jar!/BOOT-INF/classes!/templates/weeklyrep/content/weelyrep_2.xlsx

因为周报系统是使用jar启动,报错内容为无法正确的映射路径,也是情有可原,直接运行是没问题的。

错误代码

            ClassPathResource classPathResource = new ClassPathResource("templates/weeklyrep/content/weelyrep_2.xlsx");

            String templateFileName = null;
            try {
                templateFileName = classPathResource.getFile().getAbsolutePath();

            } catch (IOException e) {
                e.printStackTrace();
            }

            String filename ="weekely.xlsx";

            String downloadPath = RuoYiConfig.getDownloadPath() + filename;

            ExcelWriter excelWriter=EasyExcel.write(downloadPath).withTemplate(templateFileName).build();

正确代码

            ClassPathResource classPathResource = new ClassPathResource(pathStr);
            InputStream  fio=null;
            try {
                fio=classPathResource.getInputStream();

            } catch (IOException e) {
                e.printStackTrace();
            }

            String filename ="weekely.xlsx";

            String downloadPath = RuoYiConfig.getDownloadPath() + filename;

            ExcelWriter excelWriter=EasyExcel.write(downloadPath).withTemplate(fio).build();

直接使用ClassPathResourcegetInputStream(),不使用File即可解决

参考

springboot 中File获取resources目录下静态资源找不到文件问题FileNotFoundException(No such file or directory)

本文来自:【Java】jar启动的java程序报错FileNotFoundException-小码农,转载请保留本条链接,感谢!

温馨提示:
本文最后更新于 2022年10月14日,已超过 731 天没有更新。若文章内的图片失效(无法正常加载),请留言反馈或直接联系我
正文到此结束
本文目录