properties檔案的讀寫使用例子
package com.zyj;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.Properties;
import java.util.concurrent.BlockingQueue;
public class PropertiesIO {
//根據key讀取value
public static String readValue(String filePath, String key){
Properties props = new Properties();
String value=null;
try{
props.load(PropertiesIO.class.getClassLoader().getResourceAsStream(filePath));//此方法只讀
value = props.getProperty(key);
// in.close();
}catch(Exception e){
e.printStackTrace();
}
return value;
}
//讀取properties的全部資訊
public static void readProperties(String filePath){
Properties props = new Properties();
try{
InputStream in = new BufferedInputStream(PropertiesIO.class.getClassLoader().getResourceAsStream(filePath));
props.load(in);
Enumeration<?> en = props.propertyNames();
while(en.hasMoreElements()){
String key = (String)en.nextElement();
String property = props.getProperty(key);
System.out.println(key + " : " + property);
}
in.close();
}catch(Exception e){
e.printStackTrace();
}finally{
}
}
//寫入properties資訊
public static void writeProperties(String filePath, String parameterName, String parameterValue){
Properties props = new Properties();
try{
InputStream fis = new FileInputStream(filePath);
// InputStream fis = new BufferedInputStream(PropertiesIO.class.getClassLoader().getResourceAsStream(filePath));
//從輸入流中讀取屬性列表(鍵和元素對)
props.load(fis);
fis.close();
//呼叫Hashtable的方法put。使用getProperty方法提供並行性
//強制要求為屬性的鍵和值使用字串。返回值是Hashtable呼叫put的結果
OutputStream fos = new FileOutputStream(filePath);
props.setProperty(parameterName, parameterValue);
//以適合使用load方法載入到Properties表中的格式,將此Properties表中的屬性列表(鍵和元素對)寫入輸出流
//props.store(fos, "Update '" + parameterName + "' value");
props.store(fos,"");
fos.close();//------------------------------------important
}catch(IOException e){
e.printStackTrace();
}
}
public static void main(String[] args) {
PropertiesIO.writeProperties("D:/abcdefghijklmnopqrstuvwxyz/source/ja08/PropertiesTest/src/ziyuan.properties","a","xxx");
// System.out.println(PropertiesIO.readValue("ziyuan.properties","a"));
// PropertiesIO.readProperties("ziyuan.properties");
}
}