今天在项目中,修改excel导出文件路径的时候,之前是直接写在tomcat中的,写死的文件路径,因上次项目迁移时,忘记迁移excel模板导致模板下载报错,才有了这次修改
刚开始改的时候以为也挺简单的,修改一下路径就好了,没想到修改完成后,报资源找不到的错误
java.io.FileNotFoundException: /assets/officeModel/inventoryModel.xlsx (No such file or directory)
文件读取的java代码
File file = new File("/assets/officeModel/inventoryModel.xlsx"); FileInputStream fileInputStream = new FileInputStream(file); poiLinkage.exportExcel(fileInputStream, response, hierarchicNameMaps);
乍一看没啥问题啊,怎么不行呢,这样来来回回试了很多次,依然不行,debug时发现,Windows系统上File方法将文件路径上的 "/" 变成了 "\" ,然后无语了,看了很多的帖子说Windows上的文件路径就是反斜杠的,想了想,反正程序最终运行在linux服务器上的,索性打包了一番,结果还是找不到文件,加 "classpath:"啊,去掉static啊都试过了,没啥六卵用,但是项目上访问却可以访问到,然后就炸了,怎么搞,百度呗
幸好还找到方法了,不用File类了,改用Spring的org.springframework.core.io.ClassPathResource类,完美解决
ClassPathResource cpr = new ClassPathResource("static/assets/officeModel/inventoryModel.xlsx"); InputStream fileInputStream = cpr.getInputStream(); poiLinkage.exportExcel(fileInputStream, response, hierarchicNameMaps);
即兼容了Windows,linux上也不会有问题