java 配置資訊類 Properties 的簡單使用

來源:互聯網
上載者:User

標籤:相關   div   建立   main   row   字串類型   讀取資料   取數   方法   

Properties :(配置資訊類) 是一個表示持久性的集合 ,繼承 Hashtable ,存值是以鍵-值得方式
   主要用於生產設定檔和讀取設定檔資訊。

簡單的執行個體:

 1 import java.io.FileNotFoundException; 2 import java.io.FileReader; 3 import java.io.FileWriter; 4 import java.io.IOException; 5 import java.util.Map.Entry; 6 import java.util.Properties; 7 import java.util.Set; 8  9 public class properties {10 11     public static void main(String[] args) throws IOException {12         createPropert();13         readPropert();14     }15     16     //(一)建立配置資訊類17     public static void  createPropert() throws IOException {18         //1.建立對象19         Properties pt = new Properties();20         21         //2.設定物件資訊(索引值都是字串類型)22         pt.setProperty("初一", "1101");23         pt.setProperty("小二", "1102");24         pt.setProperty("張3", "1103");25         pt.setProperty("lisi", "1104");26         27         //3.將配置好的對象檔案存入磁碟(兩個方法都可以)28         //(1)store(new FileWriter("C:\\.."))        如果需要寫入中文時建議使用字元流29         //(2)store(new FileOutputStream(C:\\..))    位元組流30         pt.store(new FileWriter("C:\\Users\\bigerf\\Desktop\\配置流.properties"), "這是對檔案的描述資訊:");31     }32     33     34     //(二)讀取設定物件的資訊35     public static void  readPropert() throws FileNotFoundException, IOException {36         //1.建立對象37         Properties pt = new Properties();38         39         //2.根據路徑 讀取設定物件資料 load(new FileReader("C:\\.."))40         pt.load(new FileReader("C:\\Users\\bigerf\\Desktop\\配置流.properties"));41         42         //3.遍曆集合(設定物件資料)  43         //集合是可以通過foreach迴圈來遍曆的44         Set<Entry<Object, Object>> entrys = pt.entrySet();45         for (Entry<Object, Object> entry : entrys) {46             System.out.println("name:"+entry.getKey() +"    id:"+ entry.getValue());47         }48     }49 }

列印結果:

name:初一    id:1101name:lisi    id:1104name:小二    id:1102name:張3    id:1103

相關方法:

構造方法:Properties();//無預設值

     Properties(Properties defaults);  //指定預設值

配置資訊:setProperties(key,value);  //索引值都是字串類型

寫入資料:(1)store(new FileWriter("C:\\.."),"配置資訊的描述語") ;  //如果需要寫入中文時建議使用字元流

     (2)store(new FileOutputStream(C:\\..),"配置資訊的描述語");  // 位元組流

讀取資料: load(new FileReader("C:\\.."));  //字元流讀取

java 配置資訊類 Properties 的簡單使用

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.