【应用】Properties类与Properties配置文件的读写
1.Properties類與Properties配置文件
什么是Properties類
Properties(Java.util.Properties),該類主要用于讀取Java的配置文件,不同的編程語(yǔ)言有自己所支持的配置文件,配置文件中很多變量是經(jīng)常改變的,為了方便用戶的配置,能讓用戶夠脫離程序本身去修改相關(guān)的變量設(shè)置。就像在Java中,其配置文件常為.properties文件,是以鍵值對(duì)的形式進(jìn)行參數(shù)配置的。
特點(diǎn)
Properties類繼承自Hashtable類并且實(shí)現(xiàn)了Map接口,也是使用一種鍵值對(duì)的形式來(lái)保存屬性集。不過(guò)Properties有特殊的地方,就是它的鍵和值都是字符串類型。
2.Properties中的主要方法
load(InputStream inStream)
這個(gè)方法可以從.properties屬性文件對(duì)應(yīng)的文件輸入流中,加載屬性列表到Properties類對(duì)象。如下面的代碼:
Properties pro = new Properties(); FileInputStream in = new FileInputStream("a.properties"); pro.load(in); in.close();store(OutputStream out,String comments)
這個(gè)方法將Properties類對(duì)象的屬性列表保存到輸出流中。如下面的代碼:
FileOutputStream oFile = new FileOutputStream(file, "a.properties"); pro.store(oFile, "Comment"); oFile.close();如果comments不為空,保存后的屬性文件第一行會(huì)是#comments,表示注釋信息;如果為空則沒(méi)有注釋信息。
注釋信息后面是屬性文件的當(dāng)前保存時(shí)間信息。
getProperty/setProperty
這兩個(gè)方法是分別是獲取和設(shè)置屬性信息。
3.代碼實(shí)例
屬性文件a.properties如下:
name=root pass=liu key=value讀取a.properties屬性列表,與生成屬性文件b.properties。代碼如下:
import java.io.BufferedInputStream; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.util.Iterator; import java.util.Properties;public class PropertyTest {public static void main(String[] args) {Properties prop = new Properties();try{//讀取屬性文件a.propertiesInputStream in = new BufferedInputStream (new FileInputStream("a.properties"));prop.load(in); ///加載屬性列表Iterator it=prop.stringPropertyNames().iterator();while(it.hasNext()){String key=it.next();System.out.println(key+":"+prop.getProperty(key));}in.close();///保存屬性到b.properties文件FileOutputStream oFile = new FileOutputStream("b.properties", true);//true表示追加打開prop.setProperty("phone", "10086");prop.store(oFile, "The New properties file");oFile.close();}catch(Exception e){System.out.println(e);}}總結(jié)
以上是生活随笔為你收集整理的【应用】Properties类与Properties配置文件的读写的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 生物流体力学及血流动力学建模仿真技术实战
- 下一篇: async-await原理解析