gpt4 book ai didi

java - 如何在java属性文件中保存和读取Latin1字符

转载 作者:行者123 更新时间:2023-12-01 13:18:47 25 4
gpt4 key购买 nike

我正在尝试将 Latin1 字符“ÀßÖ”保存在 test.properties 文件中。但它存储为“\u00C0\u00DF\u00D6”。但我期望存储确切的值。尽可能提供帮助。

最佳答案

您可以使用重载的 store(Writer,String) 使用Writer进行存储方法,但你不应该。

保存/加载的标准方法是通过OutputStream/InputStream。 store(OutputStream,String) 的文档:

This method outputs the comments, properties keys and values in thesame format as specified in store(Writer), with the followingdifferences:

  • The stream is written using the ISO 8859-1 character encoding.
  • Characters not in Latin-1 in the comments are written as \uxxxx for their appropriate unicode hexadecimal value xxxx.
  • Characters less than \u0020 and characters greater than \u007E in property keys or values are written as \uxxxx for the appropriatehexadecimal value xxxx.

如果您使用其他机制写入数据,则任何期望标准形式的应用程序都将失败,如以下代码所示:

Path file = Paths.get("tmp.properties");
Properties write = new Properties();
write.put("key", "\u00C0\u00DF\u00D6");
try (Writer writer = Files.newBufferedWriter(file, StandardCharsets.UTF_8)) {
write.store(writer, "demo");
}
Properties read = new Properties();
try (InputStream in = Files.newInputStream(file)) {
read.load(in);
}
if (!write.get("key").equals(read.get("key"))) {
throw new IOException("expected: " + write.get("key") + "; got: "
+ read.get("key"));
}

如果转义有问题,请考虑使用替代格式,例如 JSON - JSON mandates Unicode .

关于java - 如何在java属性文件中保存和读取Latin1字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22226227/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com