我需要使用UTF-8在我的资源属性使用Java的ResourceBundle。当我直接在属性文件中输入文本时,它显示为mojibake。
我的应用程序运行在谷歌应用程序引擎。
谁能给我举个例子?我找不到这份工作。
我需要使用UTF-8在我的资源属性使用Java的ResourceBundle。当我直接在属性文件中输入文本时,它显示为mojibake。
我的应用程序运行在谷歌应用程序引擎。
谁能给我举个例子?我找不到这份工作。
当前回答
不管怎样,我的问题是文件本身的编码是错误的。使用iconv对我很有效
iconv -f ISO-8859-15 -t UTF-8 messages_nl.properties > messages_nl.properties.new
其他回答
Properties prop = new Properties();
String fileName = "./src/test/resources/predefined.properties";
FileInputStream inputStream = new FileInputStream(fileName);
InputStreamReader reader = new InputStreamReader(inputStream,"UTF-8");
我们创建了一个资源。utf8文件,包含UTF-8格式的资源,并有一个规则运行如下:
native2ascii -encoding utf8 resources.utf8 resources.properties
从Java 9开始,加载属性文件的默认值已更改为UTF-8。https://docs.oracle.com/javase/9/intl/internationalization-enhancements-jdk-9.htm
这个问题终于在Java 9中得到了解决: https://docs.oracle.com/javase/9/intl/internationalization-enhancements-jdk-9
属性文件的默认编码现在是UTF-8。
大多数现有属性文件不应受到影响:UTF-8和 ISO-8859-1对ASCII字符有相同的编码 人类可读的非ascii ISO-8859-1编码不是有效的UTF-8。如果一个 检测到无效的UTF-8字节序列,Java运行时 自动重新读取ISO-8859-1中的文件。
对于当前(2021-2)Java版本,仍然有旧的ISO-8859-1函数utils.Properties#load。
如果您使用属性。装载时必须使用ISO-8859-1。 如果使用ResourceBundle,那么UTF-8应该没问题。
请允许我引用官方文件。
PropertyResourceBundle
PropertyResourceBundle can be constructed either from an InputStream or a Reader, which represents a property file. Constructing a PropertyResourceBundle instance from an InputStream requires that the input stream be encoded in UTF-8. By default, if a MalformedInputException or an UnmappableCharacterException occurs on reading the input stream, then the PropertyResourceBundle instance resets to the state before the exception, re-reads the input stream in ISO-8859-1, and continues reading. If the system property java.util.PropertyResourceBundle.encoding is set to either "ISO-8859-1" or "UTF-8", the input stream is solely read in that encoding, and throws the exception if it encounters an invalid sequence. If "ISO-8859-1" is specified, characters that cannot be represented in ISO-8859-1 encoding must be represented by Unicode Escapes as defined in section 3.3 of The Java™ Language Specification whereas the other constructor which takes a Reader does not have that limitation. Other encoding values are ignored for this system property. The system property is read and evaluated when initializing this class. Changing or removing the property has no effect after the initialization.
https://docs.oracle.com/en/java/javase/14/docs/api/java.base/java/util/PropertyResourceBundle.html
属性#负载
从输入字节流中读取属性列表(键和元素对)。输入流采用load(Reader)中指定的简单的面向行的格式,并假定使用ISO 8859-1字符编码;即每个字节是一个拉丁字符。非拉丁字符1和某些特殊字符使用Java™语言规范3.3节中定义的Unicode转义符在键和元素中表示。
https://docs.oracle.com/en/java/javase/14/docs/api/java.base/java/util/Properties.html加载(java.io.InputStream)