更新時間:2020-05-22 15:55:34 來源:動力節點 瀏覽2174次
properties文件是我們經常需要操作一種文件,它使用一種鍵值對的形式來保存屬性集。
無論在學習上還是工作上經常需要讀取,修改,刪除properties文件里面的屬性。
本文通過操作一個properties去認識怎樣操作properties文件。
Java提供了Properties這個類Properties(Java.util.Properties),用于操作properties文件。
這是配置文件,file.properties
type=mysql
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/db?characterEncoding=utf-8
username=root
password=root
public?class?PropertiesDemo?{
?
public?static?final?Properties?p?=?new?Properties();
public?static?final?String?path?=?"file.properties";
初始化:
??/**
?*?通過類裝載器?初始化Properties
?*/
public?static?void?init()?{
//轉換成流
????InputStream?inputStream?=?????
????????PropertiesDemo.class.getClassLoader().getResourceAsStream(path);
try?{
//從輸入流中讀取屬性列表(鍵和元素對)
p.load(inputStream);
}?catch?(IOException?e)?{
e.printStackTrace();
}
}
獲取:
?/**
?*?通過key獲取value
?*?@param?key
?*?@return
?*/
public?static?String?get(String?key)?{
return?p.getProperty(key);
}
修改或者新增:
?/**
?*?修改或者新增key
?*?@param?key
?*?@param?value
?*/
public?static?void?update(String?key,?String?value)?{
p.setProperty(key,?value);
FileOutputStream?oFile?=?null;
try?{
oFile?=?new?FileOutputStream(path);
//將Properties中的屬性列表(鍵和元素對)寫入輸出流
p.store(oFile,?"");
}?catch?(IOException?e)?{
e.printStackTrace();
}?finally?{
try?{
oFile.close();
}?catch?(IOException?e)?{
e.printStackTrace();
}
}
}
刪除:
?/**
?*?通過key刪除value
?*?@param?key
?*/
public?static?void?delete(String?key)?{
p.remove(key);
FileOutputStream?oFile?=?null;
try?{
oFile?=?new?FileOutputStream(path);
p.store(oFile,?"");
}?catch?(IOException?e)?{
e.printStackTrace();
}?finally?{
try?{
oFile.close();
}?catch?(IOException?e)?{
e.printStackTrace();
}
}
}
獲取所有:
??/**
?*?循環所有key?value
?*/
public?static?void?list()?{
Enumeration?en?=?p.propertyNames();?//得到配置文件的名字
while(en.hasMoreElements())?{
String?strKey?=?(String)?en.nextElement();
String?strValue?=?p.getProperty(strKey);
System.out.println(strKey?+?"="?+?strValue);
}
}
測試:
public?static?void?main(String[]?args)?{
PropertiesDemo.init();
?
//修改
PropertiesDemo.update("password","123456");
System.out.println(PropertiesDemo.get("password"));
?
//刪除
PropertiesDemo.delete("username");
System.out.println(PropertiesDemo.get("username"));
?
????????//獲取所有
PropertiesDemo.list();
}
以上就是動力節點java培訓機構的小編針對“編程技術分享,Java讀取properties修改的文件”的內容進行的回答,希望對大家有所幫助,如有疑問,請在線咨詢,有專業老師隨時為你服務。
0基礎 0學費 15天面授
有基礎 直達就業
業余時間 高薪轉行
工作1~3年,加薪神器
工作3~5年,晉升架構
提交申請后,顧問老師會電話與您溝通安排學習