项目以jar的形式运行时Freemarker读取不到模版(springboot项目)

这篇博客探讨了在Java中无法以File对象读取jar内文件的问题,指出只能通过流的方式进行读取。作者提供了配置FreeMarker模板引擎的示例,展示了如何正确地使用SpringTemplateLoader从classpath加载资源。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这些方法都是读文件的文件的方式

//以下这种读取file的方式都不行
//方法一
String path = Thread.currentThread().getContextClassLoader().getResource("").getPath();
//方法二
File file = new ClassPathResource("generator").getFile();
//方法三
 File file = new File(System.getProperty("user.dir"));
//等等

jar中的文件不能以File的形式读取,只能以流的形式读取,如果以file形式读取会报文件找不到 : 

java.io.FileNotFoundException:/file:/usr/share/muiuo/mudey-svstem.iar!/BOOT-INF/lib/ 

java.io.FileNotFoundException: class path resource [template ]cannot be resolved to absolute file because it does not reside in the file svstem: jar:file:/usr/share/mp/dev-svstem.iar!/BOOT-INF/Lib/asdf-core-2.2.0.BETA.iar!/template 

/**
* 通过流的形式读取文件是没问题的
*/
@Slf4j
@Configuration
public class FreemarkerConfig {
    private static freemarker.template.Configuration cfg;
    @Autowired
    private ResourceLoader resourceLoader;

    @Bean
    public freemarker.template.Configuration config (){
        try {
//template:resource目录下的ftl文件放置目录
            SpringTemplateLoader templateLoader = new SpringTemplateLoader(resourceLoader, "classpath:template");
            cfg = new freemarker.template.Configuration(freemarker.template.Configuration.VERSION_2_3_23);
            cfg.setTemplateLoader(templateLoader);
            cfg.setDefaultEncoding("UTF-8");
        } catch (Exception e) {
            log.error("error:", e);
        }
        return cfg;
    }

    public freemarker.template.Configuration getCfg(){
        return cfg;
    }


}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值