「问题解决」java web项目打成jar包运行后工具类无法读取模板文件的解决方法

介绍语

本号主要是Java常用关键技术点,通用工具类的分享;以及springboot+springcloud+Mybatisplus+druid+mysql+redis+swagger+maven+docker等集成框架的技术分享;datax、kafka、flink等大数据处理框架的技术分享。文章会不断更新,欢迎码友关注点赞收藏转发!

望各位码友点击关注,冲1000粉。后面会录制一些视频教程,图文和视频结合,比如:图书介绍网站系统、抢购系统、大数据中台系统等。技术才是程序猿的最爱,码友们冲啊

如果码友觉得代码太长,可以从头到尾快速扫射一遍,了解大概即可。觉得有用后再转发收藏,以备不时之需。

正文:

项目目录结构如下:

 

我在开发博客系统的的时候,需要使用工具类FreemarkerUtil获取ftl模板文件生成html文件, idea本地运行正常,freemarker正常获取到模板并生成静态文件,如下图:

 

打包成jar包之后在服务器上运行,报如下问题:
java.io.FileNotFoundException: file:/home/myblog-0.0.1-SNAPSHOT.jar!/BOOT-INF/classes!/moban does not exist.

 

百度后大悟,打包成jar包时,不能使用new File()方式获取jar包中的文件,需要用流的方式获取。所以修改代码后,在本地idea运行正常,服务器运行也正常了。

工具类源码:
修改前源代码:
这时候传递的ftlFile参数为:/moban/help-page.ftl

 package com.javalaoniu.blog.utils;  
   
 import com.javalaoniu.blog.exception.BlogBusinessException;  
 import freemarker.template.Configuration;  
 import freemarker.template.Template;  
 import org.slf4j.Logger;  
 import org.slf4j.LoggerFactory;  
   
 import java.io.File;  
 import java.io.FileWriter;  
 import java.net.URL;  
 import java.util.Map;  
   
 public class FreemarkerUtil {  
   
     private static final Logger LOGGER = LoggerFactory.getLogger(FreemarkerUtil.class);  
   
     /**  
      * 生成静态html文件  
      *  
      * @param ftlFile  模板文件  
      * @param map      用于模板中的数据  
      * @param htmlFile 输出的文件  
      */  
     public void genHtml(String ftlFile, String htmlFile, Map map) {  
         LOGGER.info("ftlFile:{}", ftlFile);  
         LOGGER.info("htmlFile:{}", htmlFile);  
         try {  
             URL resource = this.getClass().getResource(ftlFile);  
             File mobanFile = new File(resource.getPath());  
             LOGGER.info("模板文件:{}", mobanFile.getPath());  
   
             Configuration cfg = new Configuration(Configuration.VERSION_2_3_23);  
             cfg.setDirectoryForTemplateLoading(new File(mobanFile.getParent()));  
             cfg.setDefaultEncoding("utf-8");  
             Template template = cfg.getTemplate(mobanFile.getName());  
   
             //生成静态页面  
             File outFile = new File(htmlFile);  
             if (!outFile.exists()) {  
                 // 创建目录  
                 File dir = new File(outFile.getParent());  
                 dir.mkdirs();  
             }  
             if (outFile.exists()&&!outFile.isFile()) {  
                 throw new RuntimeException("输出文件错误,它不是文件");  
             }  
             LOGGER.info("outFile.getPath:{}", outFile.getPath());  
             //String ftlPath = this.getClass().getClassLoader().getResource(ftlFile)  
   
             FileWriter fw = new FileWriter(outFile);  
             template.process(map, fw);  
             LOGGER.info("输出文件:{}", outFile.getPath());  
         } catch (Exception e) {  
             LOGGER.error("生成静态文件异常:", e);  
             throw new BlogBusinessException("生成静态文件异常", e);  
         }  
     }  
   
 }

修改后源代码:
这时候传递的ftlFile参数为:help-page.ftl

 package com.javalaoniu.blog.utils;  
   
 import com.javalaoniu.blog.exception.BlogBusinessException;  
 import freemarker.cache.ClassTemplateLoader;  
 import freemarker.template.Configuration;  
 import freemarker.template.Template;  
 import org.slf4j.Logger;  
 import org.slf4j.LoggerFactory;  
   
 import java.io.File;  
 import java.io.FileWriter;  
 import java.util.Map;  
   
 public class FreemarkerUtil {  
   
     private static final Logger LOGGER = LoggerFactory.getLogger(FreemarkerUtil.class);  
   
     /**  
      * 生成静态html文件  
      *  
      * @param ftlFile  模板文件  
      * @param map      用于模板中的数据  
      * @param htmlFile 输出的文件  
      */  
     public void genHtml(String ftlFile, String htmlFile, Map map) {  
         LOGGER.info("ftlFile:{}", ftlFile);  
         LOGGER.info("htmlFile:{}", htmlFile);  
         try {  
             LOGGER.info("模板文件:{}", ftlFile);  
   
             Configuration cfg = new Configuration(Configuration.VERSION_2_3_23);  
             //cfg.setDirectoryForTemplateLoading(new File(mobanFile.getParent()));// 打成jar后运行获取到的路径不对  
             //cfg.setClassForTemplateLoading(FreemarkerUtil.class, "moban");// 打成jar后运行获取到的路径不对  
             cfg.setTemplateLoader(new ClassTemplateLoader(  
                 this.getClass().getClassLoader(),  "/moban"));  
             cfg.setDefaultEncoding("utf-8");  
             Template template = cfg.getTemplate(ftlFile);  
   
             //生成静态页面  
             File outFile = new File(htmlFile);  
             if (!outFile.exists()) {  
                 // 创建目录  
                 File dir = new File(outFile.getParent());  
                 dir.mkdirs();  
             }  
             if (outFile.exists()&&!outFile.isFile()) {  
                 throw new RuntimeException("输出文件错误,它不是文件");  
             }  
             LOGGER.info("outFile.getPath:{}", outFile.getPath());  
             //String ftlPath = this.getClass().getClassLoader().getResource(ftlFile)  
   
             FileWriter fw = new FileWriter(outFile);  
             template.process(map, fw);  
             LOGGER.info("输出文件:{}", outFile.getPath());  
         } catch (Exception e) {  
             LOGGER.error("生成静态文件异常:", e);  
             throw new BlogBusinessException("生成静态文件异常", e);  
         }  
     }  
   
 }
 ​

鄙人编码十年多,在项目中也积累了一些工具类,很多工具类在每个项目都有在用,很实用。大部分是鄙人封装的,有些工具类是同事封装的,有些工具类已经不记得是ctrl+c的还是自己封装的了,现在有空就会总结项目中大部分的工具类,分享给各位码友。如果文章中涉及的代码有侵权行为请通知鄙人处理。

计划是先把工具类整理出来,正所谓工欲善其事,必先利其器。项目中不管是普通单体项目还是多模块maven项目或是分布式微服务,一部分功能模块都是可以重用的,工具类模块就是其中之一。

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程序员阿宁

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值