public static void main(String[] args) throws IOException{
WriteProperties("E:\\workspace\\ch01\\text.properties", "add2","2121");
}
//根据key读取value
public static String GetValueByKey(String filePath,String key){
Properties pps = new Properties();
try{
InputStream in= new BufferedInputStream(new FileInputStream(filePath));
pps.load(in);
String value = pps.getProperty(key);
System.out.println(key + "=" + value);
return value;
}catch(IOException e){
e.printStackTrace();
return null;
}
}
//读取配置文件的全部信息
@SuppressWarnings("rawtypes")
public static void GetAllProperties(String filePath) throws IOException{
Properties pps = new Properties();
InputStream in = new BufferedInputStream(new FileInputStream(filePath));
pps.load(in);
Enumeration num = pps.propertyNames(); //获取配置文件中的所有属性名enumeration
while(num.hasMoreElements()){
String key= (String)num.nextElement();
String value=pps.getProperty(key);
System.out.println(key + "=" + value);
}
}
//写入Properties信息
public static void WriteProperties(String filePath,String pKey,String pValue) throws IOException {
Properties pps = new Properties();
InputStream in= new FileInputStream(filePath);
pps.load(in);
OutputStream out = new FileOutputStream(filePath);
pps.setProperty(pKey, pValue);
pps.store(out, "Update " + pKey + " name");
}
}
结果:test.properties文件
#Update add2 name
#Tue Jun 30 17:07:55 CST 2015
age=23
name=linyuhuan
weight=140
add2=2121
long=212