properties文件是我們經(jīng)常需要操作一種文件,它使用一種鍵值對(duì)的形式來(lái)保存屬性集。
無(wú)論在學(xué)習(xí)上還是工作上經(jīng)常需要讀取,修改,刪除properties文件里面的屬性。
本文通過(guò)操作一個(gè)properties去認(rèn)識(shí)怎樣操作properties文件。
Java提供了Properties這個(gè)類(lèi)Properties(Java.util.Properties),用于操作properties文件。
這是配置文件,file.properties
type=mysqldriver=com.mysql.jdbc.Driverurl=jdbc:mysql://localhost:3306/db?characterEncoding=utf-8username=rootpassword=rootpublic?class?PropertiesDemo?{? public?static?final?Properties?p?=?new?Properties(); public?static?final?String?path?=?"file.properties";
初始化:
?? public?static?void?init()?{ //轉(zhuǎn)換成流 ????InputStream?inputStream?=?????????????PropertiesDemo.class.getClassLoader().getResourceAsStream(path); try?{ //從輸入流中讀取屬性列表(鍵和元素對(duì)) p.load(inputStream); }?catch?(IOException?e)?{ e.printStackTrace(); } }
獲?。?nbsp;
? public?static?String?get(String?key)?{ return?p.getProperty(key); }
修改或者新增:
? public?static?void?update(String?key,?String?value)?{ p.setProperty(key,?value); FileOutputStream?oFile?=?null; try?{ oFile?=?new?FileOutputStream(path); //將Properties中的屬性列表(鍵和元素對(duì))寫(xiě)入輸出流 p.store(oFile,?""); }?catch?(IOException?e)?{ e.printStackTrace(); }?finally?{ try?{ oFile.close(); }?catch?(IOException?e)?{ e.printStackTrace(); } } }
刪除:
? 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(); } } }
獲取所有:
?? 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); } }
測(cè)試:
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();}
以上就是長(zhǎng)沙達(dá)內(nèi)教育java培訓(xùn)機(jī)構(gòu)的小編針對(duì)“編程技術(shù)分享,Java讀取properties修改的文件”的內(nèi)容進(jìn)行的回答,希望對(duì)大家有所幫助,如有疑問(wèn),請(qǐng)?jiān)诰€咨詢(xún),有專(zhuān)業(yè)老師隨時(shí)為你服務(wù)。