源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

Java实现的读取资源文件工具类ResourcesUtil实例【可动态更改值的内容】

  • 时间:2022-06-04 01:24 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:Java实现的读取资源文件工具类ResourcesUtil实例【可动态更改值的内容】
本文实例讲述了Java实现的读取资源文件工具类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<String> getKeyList(String baseName) {
    ResourceBundle rb = ResourceBundle.getBundle(baseName, getLocale());
    List<String> reslist = new ArrayList<String>();
    Set<String> keyset = rb.keySet();
    for (Iterator<String> 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}条,<a href="{2}" target="_blank">点击查看失败信息</a>
    System.out.println(getValue("conf.messages", "908", new Object[] { 100, 200 }));
  }
}

更多关于java算法相关内容感兴趣的读者可查看本站专题:《[url=http://www.1sucai.cn/Special/687.htm]Java文件与目录操作技巧汇总[/url]》、《[url=http://www.1sucai.cn/Special/632.htm]Java数据结构与算法教程[/url]》、《[url=http://www.1sucai.cn/Special/830.htm]Java操作DOM节点技巧总结[/url]》和《[url=http://www.1sucai.cn/Special/682.htm]Java缓存操作技巧汇总[/url]》 希望本文所述对大家java程序设计有所帮助。
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部