国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Java > 正文

Java 讀寫Properties配置文件詳解

2019-11-26 13:32:00
字體:
來源:轉載
供稿:網友

Java 讀寫Properties配置文件

1.Properties類與Properties配置文件

  Properties類繼承自Hashtable類并且實現了Map接口,也是使用一種鍵值對的形式來保存屬性集。不過Properties有特殊的地方,就是它的鍵和值都是字符串類型。

2.Properties中的主要方法

(1)load(InputStream inStream)

   這個方法可以從.properties屬性文件對應的文件輸入流中,加載屬性列表到Properties類對象。如下面的代碼:

Properties pro = new Properties();FileInputStream in = new FileInputStream("a.properties");pro.load(in);in.close();

(2)store(OutputStream out, String comments)

   這個方法將Properties類對象的屬性列表保存到輸出流中。如下面的代碼:

FileOutputStream oFile = new FileOutputStream(file, "a.properties");pro.store(oFile, "Comment");oFile.close();

  如果comments不為空,保存后的屬性文件第一行會是#comments,表示注釋信息;如果為空則沒有注釋信息。

  注釋信息后面是屬性文件的當前保存時間信息。

(3)getProperty/setProperty

   這兩個方法是分別是獲取和設置屬性信息。

3.代碼實例

 屬性文件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.properties      InputStream in = new BufferedInputStream (new FileInputStream("a.properties"));      prop.load(in);   ///加載屬性列表      Iterator<String> 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);    }  } }

感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 富平县| 佛冈县| 南部县| 凤冈县| 太白县| 仙桃市| 亳州市| 石城县| 中西区| 弥勒县| 平潭县| 银川市| 平湖市| 民乐县| 高邮市| 汶上县| 桂阳县| 宜都市| 弋阳县| 华蓥市| 恩平市| 乌海市| 东城区| 息烽县| 济宁市| 张家港市| 长寿区| 茂名市| 克拉玛依市| 龙山县| 宣汉县| 蒲城县| 阳原县| 湖南省| 泸西县| 博兴县| 正宁县| 临湘市| 保德县| 饶平县| 马龙县|