解决 获取 ValidationMessages.properties 值乱码

当你在Java应用中遇到从ValidationMessages.properties等资源文件中读取的国际化信息出现乱码的问题时,通常是字符编码设置不匹配导致的。以下是几种可能的解决办法:

1. 确保文件本身编码正确

首先,确保你的ValidationMessages.properties文件是使用正确的编码(如UTF-8)保存的。许多文本编辑器允许你选择文件的编码方式。如果使用的是IDE(如IntelliJ IDEA或Eclipse),在保存文件时应指定为UTF-8无BOM格式。

2. 配置ResourceBundle.Control

Java的ResourceBundle类默认使用ISO-8859-1来加载属性文件。为了支持UTF-8等其他编码,你可以自定义一个ResourceBundle.Control来指定加载时的字符集。

public class Utf8Control extends ResourceBundle.Control {
    @Override
    public ResourceBundle newBundle(String baseName, Locale locale, String format, ClassLoader loader, boolean reload)
            throws IllegalAccessException, InstantiationException, IOException {
        // The below is a copy of the default implementation.
        String bundleName = toBundleName(baseName, locale);
        String resourceName = toResourceName(bundleName, "properties");
        ResourceBundle bundle = null;
        InputStream stream = null;
        if (reload) {
            URL url = loader.getResource(resourceName);
            if (url != null) {
                URLConnection connection = url.openConnection();
                if (connection != null) {
                    connection.setUseCaches(false);
                    stream = connection.getInputStream();
                }
            }
        } else {
            stream = loader.getResourceAsStream(resourceName);
        }
        if (stream != null) {
            try {
                // Only this line is changed to make it to read properties files as UTF-8.
                bundle = new PropertyResourceBundle(new InputStreamReader(stream, StandardCharsets.UTF_8));
            } finally {
                stream.close();
            }
        }
        return bundle;
    }
}

然后,使用这个自定义的Control来加载资源包:

ResourceBundle bundle = ResourceBundle.getBundle("ValidationMessages", new Utf8Control());
String message = bundle.getString("your.key");

3. IDE和构建工具配置

确保你的IDE和构建工具(如Maven或Gradle)在编译和打包过程中也正确处理了字符编码。例如,在Maven的pom.xml中可以添加如下配置来指定资源文件的编码:

<project>
  ...
  <build>
    ...
    <resources>
      <resource>
        <directory>src/main/resources</directory>
        <filtering>true</filtering>
        <encoding>UTF-8</encoding>
      </resource>
    </resources>
    ...
  </build>
  ...
</project>

通过上述方法,你应该能够解决从ValidationMessages.properties等资源文件中读取值时出现的乱码问题。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值