如果转载本文请写明出处,谢谢!
configuration.properties中的文件内容如下
#name
#Mon Aug 20 13:58:41 CST 2012
\u4F5C\u7528=\u7528\u6765\u6D4B\u8BD5\u73A9\u7684\uFF0C\u5475\u5475...
name=testGetPropertiesValue
value=127.0.0.1
driver=oracle
\u59D3\u540D=\u674E
*********************************************************************************************************************
//ConfigUtil.java
package liweiTest;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
public class ConfigUtil
{
private static Properties props = null;
static
{
props = new Properties();
reLoad();
}
//加载属性文件
private static void reLoad()
{
try
{
InputStream input = ConfigUtil.class.getResourceAsStream("/configuration.properties");
props.load(input);
}
catch (Exception ex)
{
System.out.println("exceptiom:"+ex);
}
}
//获取当前文件的路径,返回成FileOutputStream
public static FileOutputStream getUrl()
{
String url = ConfigUtil.class.getClassLoader().getResource(".").getPath();
FileOutputStream file = null;
try
{
file = new FileOutputStream(url + File.separator + "configuration.properties");
}
catch (FileNotFoundException e)
{
e.printStackTrace();
} // 指定要操作的文件
return file;
}
//获取某个键的属性
public static String getString(String name)
{
try
{
return props.getProperty(name);
} catch (Exception ex)
{
System.out.println("exceptiom:"+ex);
return null;
}
}
//对configuration.properties进行遍历,获取全部的键值和属性值
public static HashMap<String,String> getAll()
{
Set<String> names = props.stringPropertyNames();
HashMap<String,String> map = new HashMap<String,String>();
for(String name:names)
{
map.put(name, props.getProperty(name));
}
return map;
}
//写入一对属性到 configuration.properties文件中
public static void setValue(String name,String value)
{
props.setProperty(name,value) ; // 设置属性
try
{
props.store(getUrl(),"放入一对属性");
}
catch (IOException e)
{
e.printStackTrace();
} // 保存属性到普通文件
}
//同时写入多个属性到 configuration.properties文件中
public static void setAllValue(Map<String,String> map)
{
for(Map.Entry<String,String>me:map.entrySet())
{
props.setProperty(me.getKey(),me.getValue()) ; // 设置属性
}
try
{
props.store(getUrl(),"放入多个属性");
}
catch (IOException e)
{
e.printStackTrace();
} // 保存属性到普通文件
}
public static void main(String[] args)
{
System.out.println(ConfigUtil.getString("name"));
setValue("姓名", "李WEI123");
HashMap<String ,String> map = new HashMap<String,String>();
map.put("driver","oracle");
map.put("value", "127.0.0.1");
map.put("作用", "用来测试玩的,呵呵...");
setAllValue(map);
System.out.println(ConfigUtil.getString("姓名"));
HashMap<String ,String> map2 = getAll();
for(Map.Entry<String, String>m:map2.entrySet())
{
System.out.println(m.getKey()+" = "+m.getValue());
}
}
}