SpringBoot项目打成jar包之后,无法读取resource目录下的文件

项目中有一需求,原先在超市小程序中购物完成之后,需要在核验机器上进行核验操作,才能完成整个购物流程。但是核验机器有时候有问题,无法进行核验操作,所以需要在商户后台页面中将订单明细导出pdf文件。

在这个需求中:导出pdf文件需要读取设置的pdf模板和中文字体。
代码在本地测试的时候,通过如下代码进行读取文件:
File file = ResourceUtils.getFile(path+fileName);
但是项目在发布到服务器上之后,却总是报空指针异常,经过日志定位发现,问题在于项目打包成jar文件之后,无法读取模板和中文字体。
必须以流的方式读取这两个文件。
代码如下:

//读取pdf的模板
 ClassPathResource tempResource = new ClassPathResource("template.html");
 ClassPathResource simResource = new ClassPathResource("simsun.ttc");
 File tempFile = writeFile("", "template.html", tempResource);
 File simFile = writeFile("", "simsun.ttc", simResource);
private File writeFile(String filePath, String fileName, ClassPathResource resource) throws IOException {
        InputStream in = null;
        FileOutputStream out = null;
        File newFile = new File(filePath + fileName);
        try {
            in = resource.getInputStream();
            //循环存放临时数据
            byte[] buff = new byte[1024];
            out = new FileOutputStream(newFile);
            int length = 0;
            while ((length = in.read(buff, 0, 100)) > 0) {
                out.write(buff, 0, length);
            }
            in.close();
            out.close();
        } catch (Exception e) {
            logger.error("writeFile failed.", e);
        }
        return newFile;

    }

以留的方式读取文件。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值