JAVA工具类(11)---读取资源文件工具类ResourcesUtil (可以动态更改值的内容)

package com.gcloud.common;

import java.io.Serializable;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.ResourceBundle;
import java.util.Set;

/**
 * 资源文件读取工具类
 * 
 */
public class ResourcesUtil implements Serializable {

    private static final  String FILENAME = "conf.messages";

    private static final long serialVersionUID = -7657898714983901418L;

    /**
     * 系统语言环境,默认为中文zh
     */
    public static final String LANGUAGE = "zh";

    /**
     * 系统国家环境,默认为中国CN
     */
    public static final String COUNTRY = "CN";

    private static Locale getLocale() {
        Locale locale = new Locale(LANGUAGE, COUNTRY);
        return locale;
    }

    /**
     * 根据语言、国家、资源文件名和key名字获取资源文件值
     * @param baseName 资源文件名
     * @param section key名字
     * @return 值
     */
    private static String getProperties(String baseName, String section) {
        try {
            ResourceBundle rb = ResourceBundle.getBundle(baseName, getLocale());
            return (String) rb.getObject(section);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 通过key从资源文件读取内容
     * @param fileName 资源文件名
     * @param key 索引
     * @return 索引对应的内容
     */
    public static String getValue(String fileName, String key) {
        return getProperties(fileName, key);
    }

    /**
     * 获取默认
     * @param key
     * @return
     */
    public static String getValue(String key) {
        return getProperties(FILENAME, key);
    }

    public static List getKeyList(String baseName) {
        ResourceBundle rb = ResourceBundle.getBundle(baseName, getLocale());
        List reslist = new ArrayList();
        Set keyset = rb.keySet();
        for (Iterator it = keyset.iterator(); it.hasNext();) {
            String lkey = (String) it.next();
            reslist.add(lkey);
        }
        return reslist;
    }

    /**
     * 通过key从资源文件读取内容,并格式化
     * @param fileName 资源文件名
     * @param key  索引
     * @param objs 格式化参数
     * @return 格式化后的内容
     */
    public static String getValue(String fileName, String key, Object[] objs) {
        String pattern = getValue(fileName, key);
        return MessageFormat.format(pattern, objs);
    }

    public static void main(String[] args) {
        //908=操作成功{0}条,失败{1}条,点击查看失败信息
        System.out.println(getValue("conf.messages", "908", new Object[] { 100, 200 }));
    }
}

———————————————————————
(java 架构师全套教程,共760G, 让你从零到架构师,每月轻松拿3万)
有需求者请进站查看,非诚勿扰

https://item.taobao.com/item.htm?spm=686.1000925.0.0.4a155084hc8wek&id=555888526201

01.高级架构师四十二个阶段高
02.Java高级系统培训架构课程148课时
03.Java高级互联网架构师课程
04.Java互联网架构Netty、Nio、Mina等-视频教程
05.Java高级架构设计2016整理-视频教程
06.架构师基础、高级片
07.Java架构师必修linux运维系列课程
08.Java高级系统培训架构课程116课时
(送:hadoop系列教程,java设计模式与数据结构, Spring Cloud微服务, SpringBoot入门)
——————————————————————–

你可能感兴趣的:(java-工具类)