欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

FreeMarker中文乱码的问题。

程序员文章站 2022-03-18 20:41:30
...

1、在开发环境生产无乱码,打包后在生产环境出现乱码
直接上代码:修改前代码

 TemplateEngine engine = TemplateUtil.createEngine(new TemplateConfig(properties.getPath().getPath(), TemplateConfig.ResourceMode.FILE));
 ...
 private static void genFile(File file, Template template, Map<String, Object> map) throws IOException {
        // 生成目标文件
        Writer writer = null;
        try {
            FileUtil.touch(file);
             writer = new FileWriter(file);
             template.render(map, writer); 

        } catch (TemplateException | IOException e) {
            throw new RuntimeException(e);
        } finally {
            assert writer != null;
            writer.close();
        }
    }

修改后代码:

 Charset charset =  Charset.forName("UTF-8");
                TemplateEngine engine = TemplateUtil.createEngine(new TemplateConfig(charset,properties.getPath().getPath(), TemplateConfig.ResourceMode.FILE));
  ...
               
private static void genFile(File file, Template template, Map<String, Object> map) throws IOException {
        // 生成目标文件
        Writer writer = null;
        try {
            FileUtil.touch(file);
            //  writer = new FileWriter(file);
            // template.render(map, writer);
             writer = new PrintWriter(file,"UTF-8");
             template.render(map, writer);

        } catch (TemplateException | IOException e) {
            throw new RuntimeException(e);
        } finally {
            assert writer != null;
            writer.close();
        }
    }
相关标签: freemarket