java 讀取資源文件並且動態設置資源裏面的參數demo

 test.properties:

test001={0}helloworld{1}
test002=\u4E16\u754C\u4F60\u597D\uFF01

java代碼:

package com.jw.util;

import java.io.IOException;
import java.io.InputStream;
import java.text.MessageFormat;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Properties;

public class ReadProperties {

 private static Properties p;
 /**
  * 獲取Properties對象
  * @param fname
  * @return
  */
 public static Properties getperProperties(String fname){
  InputStream in=ClassLoader.getSystemResourceAsStream(fname);
  p=new Properties();
  try {
   p.load(in);
   return p;
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  return null;
 }
 
 /**
  * 根據鍵獲取值
  * @param key
  * @return
  */
 public static String getValue(String key){
  return p.getProperty(key);
 }
 
 public static HashMap<Object, String> getAll(){
  Enumeration e=p.elements();
  
  HashMap<Object,String> map=new HashMap<Object, String>();
  while(e.hasMoreElements()){
   Object o=e.nextElement();
   map.put(o, (String)p.get(o));
  }
  return map;
 }
 
 /**
  * 設置默認值
  * @param key
  * @param defaultValue
  * @return
  */
 public static String setDefaultValue(String key,String value){
  String [] strarr=value.split(",");
  String value1=p.getProperty(key);
  String str1=MessageFormat.format(value1, strarr);
  System.out.println("格式化的字符串:"+str1);
  return  str1;
 }
 /**
  * @param args
  */
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  String  fname="test.properties";
  ReadProperties.getperProperties(fname);
 
  String  str=ReadProperties.getValue("test002");
  System.out.println("str:"+str);
  String str1=ReadProperties.setDefaultValue("test001","劉德華說:,388339399");
  System.out.println("str1:"+str1);
 }

}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章