从properties文件获取中文key

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");

 4,根据value获取key

    private String getPropertiesKey(String type) {
        Set<String> strings = deviceType.keySet();
        HashMap<String, Integer> stringIntegerHashMap = new HashMap<>();
        ArrayList<String> integers = new ArrayList<>();
        strings.forEach(e -> {
            String deviceTypeInts = deviceType.getString(e);
            if (type.equals(deviceTypeInts)) {
                integers.add(e);
            }
        });
        return integers.get(0);
    }

 

posted @ 2023-05-15 14:36  党王  阅读(218)  评论(0)    收藏  举报