您的位置:首页 > 编程语言 > Java开发

java 读取资源文件并且动态设置资源里面的参数demo

2011-07-09 13:58 751 查看
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);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐