栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

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

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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类型

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/936830.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号