首页 > 其他分享 >从properties文件获取中文key

从properties文件获取中文key

时间:2023-05-15 14:45:36浏览次数:34  
标签:中文 java String locale util ResourceBundle key import properties

1,修改编码格式为UTF-8

 2,对resourceBundle解决实现实体类,修改编码格式

package com.ruoyi.web.controller.utool;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.PropertyResourceBundle;
import java.util.ResourceBundle;

/**
 * @author 党远洋
 * @since 2023/5/15
 */
public class UnicodeResourceBundle extends ResourceBundle.Control {
    @Override
    public ResourceBundle newBundle(String baseName, java.util.Locale locale, String format,
                                    ClassLoader loader, boolean reload)
        throws IllegalAccessException, InstantiationException, IOException {
        String bundleName = toBundleName(baseName, locale);
        String resourceName = toResourceName(bundleName, "properties");

        try (InputStream stream = loader.getResourceAsStream(resourceName)) {
            if (stream != null) {
                return new PropertyResourceBundle(new InputStreamReader(stream, StandardCharsets.UTF_8));
            }
        }

        return super.newBundle(baseName, locale, format, loader, reload);
    }

    @Override
    public boolean needsReload(String baseName, java.util.Locale locale, String format, ClassLoader loader,
                               ResourceBundle bundle, long loadTime) {
        return true; // Always reload to support dynamic resource changes
    }
}

3,调用位置添加修改后的设置

 ResourceBundle deviceType = ResourceBundle.getBundle("DeviceType",new UnicodeResourceBundle());
        String string1 = deviceType.getString("中文key");

 

标签:中文,java,String,locale,util,ResourceBundle,key,import,properties
From: https://www.cnblogs.com/dangwang/p/17401823.html

相关文章