java中操作properties檔案
private String loadSysPath(){
String temp = "./cluster/siteId/conf/netMap.properties";
if(temp.indexOf("siteId")!=-1){
String siteId= ContextHolder.getContext().getSiteId();
temp = temp.replaceAll("siteId", siteId);
}
return temp;
}
/**
* 修改郵箱上限值
* @param key 郵箱關鍵字
* @param value 郵箱上限值
* @return
*/
public void changePropertiesValue( @Read(key = "key") String key,@Read(key = "value") String value) {
Properties p = new Properties();
FileInputStream in;
try {
String propertiesPath = this.loadSysPath();
in = new FileInputStream(propertiesPath);
p.load(in);
in.close();
p.setProperty(key,value);//設定屬性值,如屬性不存在新建
FileOutputStream out=new FileOutputStream(propertiesPath);//輸出流
p.store(out,"netMap set");//設定屬性頭,如不想設定,請把後面一個用""替換掉
out.flush();//清空快取,寫入磁碟
out.close();//關閉輸出流
} catch (Exception e) {
logger.error("changePropertiesValue failed in ManageIndexAction",e);
}
}
/**
* 獲取郵箱上限值
* @param key 郵箱關鍵字
* @return 郵箱儲存最大值,-1為讀取數值失敗
*/
public String getNetMapPropertiesValue(String key) {
String s = "";
String type = "0";
Properties p = new Properties();//載入屬性檔案讀取類
FileInputStream in=null;
OutputStreamWriter os=null;
String propertiesPath = this.loadSysPath();
try {
File file= new File(propertiesPath);
//判斷檔案是否存在,不存在建立並新增該郵箱的預設上限數量
if(!file.exists()){
String ss = propertiesPath.substring(0, propertiesPath.lastIndexOf("/"));
File root= new File(ss);
if (!root.exists()) {
root.mkdirs();
}
os = new OutputStreamWriter(new FileOutputStream(file));
os.close();
changePropertiesValue(key,"0");
}
//propertiesFileName如test.properties
in = new FileInputStream(propertiesPath);//以流的形式讀入屬性檔案
p.load(in);//屬性檔案將該流加入的可被讀取的屬性中
in.close();//讀完了關閉
s = p.getProperty(key);//取得對應的屬性值
if(StringUtils.isBlank(s)){
changePropertiesValue(key,"0");
s = "0";
}
type = s;
} catch (Exception e) {
logger.error(" getMaxNumByMsgBoxType error in PrivateMessageServiceImpl ",e);
}finally{
try{
if(in!= null){
in.close();
}if(os != null){
os.close();
}
}catch(Exception ex){
logger.error(ex);
}
}
return type;
}