欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

spring boot 项目打成jar包后读取文件问题

程序员文章站 2022-04-28 09:09:39
...

java.io.FileNotFoundException: class path resource [xxx.xls]
cannot be resolved to absolute file path because it does not reside in the file system: jar:file:/D:/新建文件夹/xxx.jar!/BOOT-INF/classes!/export/xxx.xls
at org.springframework.util.ResourceUtils.getFile(ResourceUtils.java:217)

在war包运行情况下是没问题的,路径其实是对的,spring是不允许直接访问jar包内的文件的,所以会报错,然后改写下读取文件的方式

  • 精简的老代码方式

      ClassPathResource resource = new ClassPathResource("XXX.xls");
      File file = resource.getFile();
    
  • 修改后的精简代码

      ClassPathResource resource = new ClassPathResource("application.yml");
      InputStream inputStream = resource.getInputStream();
    
  • 笔者老代码

         public String generateExcel(String sourceFileName, String destFileName, Map<String, Object> params) throws Exception{
              XLSTransformer transformer = new XLSTransformer();
      
      //        URL url = this.getClass().getClassLoader().getResource("");
      //
      //        assert url != null;
              ClassPathResource resource = new ClassPathResource(EXPORT_RESOURCE_PATH + sourceFileName);
      
              transformer.transformXLS( resource.getFile().getPath(), params, TMP_DIR + destFileName);
              return TMP_DIR + destFileName;
          }
    
  • 笔者新代码

         public String generateExcel(String sourceFileName, String destFileName, Map<String, Object> params) throws Exception{
      //        XLSTransformer transformer = new XLSTransformer();
      
      //        URL url = this.getClass().getClassLoader().getResource("");
      //
      //        assert url != null;
              ClassPathResource resource = new ClassPathResource(EXPORT_RESOURCE_PATH + sourceFileName);
      
              InputStream inputStream = resource.getInputStream();
      
      
      //        transformer.transformXLS( resource.getFile().getPath(), params, TMP_DIR + destFileName);
              transformXLS4Jar( inputStream, params, TMP_DIR + destFileName);
              return TMP_DIR + destFileName;
          }
    
        public  void transformXLS4Jar(InputStream is, Map beanParams, String destFilePath) throws ParsePropertyException, IOException, InvalidFormatException {
          XLSTransformer xlsTransformer = new XLSTransformer();
          org.apache.poi.ss.usermodel.Workbook workbook = xlsTransformer.transformXLS(is, beanParams);
          OutputStream os = new BufferedOutputStream(new FileOutputStream(destFilePath));
          workbook.write(os);
          is.close();
          os.flush();
          os.close();
      }