我有一个Gradle kts的 spring 启动项目,我正在使用独立的Freemarker库implementation("org.freemarker:freemarker:2.3.32")作为前端的文本模板.

我编写了以下代码:

Configuration cfg = new Configuration(Configuration.VERSION_2_3_32);
cfg.setDirectoryForTemplateLoading(new ClassPathResource("templates").getFile());
cfg.setDefaultEncoding("utf-8");
cfg.setOutputEncoding("utf-8");

Template template = cfg.getTemplate("template.ftl");
System.out.println("template=" + template);

Map<String, Object> data = new HashMap<>();
data.put("vehicles", List.of(new Vehicle("auto", 60), new Vehicle("koloběžka", 5)));

StringWriter stringWriter = new StringWriter();
template.process(data, stringWriter);
String result = stringWriter.toString();

System.out.println(result);

模板文件template.ftl包含(用于测试目的):

jůůů

我传递给模板的数据("koloběžka")和模板本身("jůůů")都包含捷克语字符.

Problem
模板文件的编码是utf-8(至少我在Intelligence j中看到的是这样).
如果我没有在Configuration对象上设置默认编码,它将使用我的语言环境中的编码(我猜),也就是"windows-1250".然后正确打印模板(template=行)(变音符号).
但是,如果我将默认编码显式设置为utf-8,则该行打印j���.

Question
这怎么可能?
我假设如果模板和Configuration都使用utf-8,那么变音符号应该是正确的红色.
另一种方式也困扰着我--Configuration对象默认使用的编码windows-1250怎么可能能够很好地从utf-8编码文件中读取变音符号呢?

推荐答案

您的问题是您正在使用的控制台未正确设置为打印UTF-8.你应该能够在PowerShell中做到这一点,但目前我发现很难找到做到这一点的方法.

更新:在我的Java控制台上使用PowerShell时,以下方法对我很有效: $OutputEncoding = [Console]::InputEncoding = [Console]::OutputEncoding = New-Object System.Text.UTF8Encoding个 执行代码: System.out.println(new Vehicle("koloběžka", 5)); 输出:

PS C:\Users\goose> java Vehicle
name=koloběžka,id=5
PS C:\Users\goose> 

Java相关问答推荐

在现有Json文件中添加新记录

编译期间错误(Java 0000)Android .Net MAUI

我的scala文件失败了Scala.g4 ANTLR语法

空手道比赛条件

如何使用jooq generator将表名和列名映射为人类可读的?

是否保证在事务性块的末尾标记违反约束?

';com.itextpdf.ext.html.WebColors已弃用

如何修复IndexOutOfBoundsException在ClerView适配器的onRowMoved函数?

无法在Java中处理PayPal支付响应

Java17支持哪个MapR版本?

SpringBoot:在条件{Variable}.isBlank/{Variable}.isEmpty不起作用的情况下进行路径变量验证

在java中使用不同的application.properties-jar而不使用Spring

Java嵌套流查找任意值

本机方法(JNI)总是编译的吗?

JavaFX,GridPane:在GridPane的列中生成元素将保持所有列的宽度

如何在Java中的重写方法参数中强制(Enum)接口实现?

TinyDB问题,无法解析符号';上下文&

使用StringBuilder和append方法创建字符串时Java字符串内部方法的问题

始终使用Spring Boot连接mongodb上的测试数据库

当我将鼠标悬停在javafxTextArea上时,如何更改鼠标光标?