java打包过运行时后访问包所在目录文件

打包过运行时后访问包所在目录文件

有这样一种场景,在我们使用word模板导出word时,需要加载模板,但是deepoove.poi模板解析只能解析绝对路径,发布时应该加上该模板的路径。
那么这样的写法对后期维护极度不友好,所以应该免配置,写法如下:


            ApplicationHome ah = new ApplicationHome(getClass());
            File file = ah.getSource();

仅仅两行代码,就能拿到我们当前运行的jar文件,然后获取jar包的父级目录的目标文件

file.getParentFile().getPath()+"/templates/qualityTemplate.docx"

以下是我用deepoove.poi导出word示例,希望对你有帮助

XWPFTemplate template = XWPFTemplate.compile(file.getParentFile().getPath()+"/templates/qualityTemplate.docx", config).render(
                    data
            );
            String fileName = "巡检记录.docx";
            String filename = new String(fileName.getBytes("utf-8"));
            response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document;charset=UTF-8");

            response.addHeader("Content-Disposition","attachment;fileName=" + URLEncoder.encode(filename,"UTF-8"));

            ServletOutputStream out = response.getOutputStream();
            BufferedOutputStream bos = new BufferedOutputStream(out);
            template.write(bos);
            bos.flush();
            out.flush();
            PoitlIOUtils.closeQuietlyMulti(template, bos, out); //关闭流

其中data为我们需要的数据,为map类型

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值