21. Java基礎之Properties類

Java基礎之Properties類

java.util.Properties 繼承於 Hashtable ,來表示一個持久的屬性集。它使用鍵值結構存儲數據,每個鍵及其對應值都是一個字符串。該類也被許多Java類使用,比如獲取系統屬性時, System.getProperties 方法就是返回一個 Properties 對象。

Properties

  • public Object setProperty(String key, String value): 保存一對屬性。
  • public String getProperty(String key) :使用此屬性列表中指定的鍵搜索屬性值。
  • public Set<String> stringPropertyNames():所有鍵的名稱的集合。
    public static void main(String[] args) throws FileNotFoundException {
        // 創建屬性集對象
        Properties properties = new Properties();
        
        // 添加鍵值對元素
        properties.setProperty("filename", "a.txt");
        properties.setProperty("length", "209385038");
        properties.setProperty("location", "D:\\a.txt");
        
        // 打印屬性集對象
        System.out.println(properties);
        
        // 通過鍵,獲取屬性值
        System.out.println(properties.getProperty("filename"));
        System.out.println(properties.getProperty("length"));
        System.out.println(properties.getProperty("location"));
        
        // 遍歷屬性集,獲取所有鍵的集合
        Set<String> strings = properties.stringPropertyNames();
        // 打印鍵值對
        for (String key : strings ) {
            System.out.println(key+"--"+properties.getProperty(key));
        }
    }

與IO流相關的方法

public void load(InputStream inStream): 從字節輸入流中讀取鍵值對。

參數中使用了字節輸入流,通過流對象,可以關聯到某文件上,這樣就能夠加載文本中的數據了

    public static void main(String[] args) throws FileNotFoundException {
        // 創建屬性集對象
        Properties pro = new Properties();
        // 加載文本中信息到屬性集
        pro.load(new FileInputStream("read.txt"));
        // 遍歷集合並打印
        Set<String> strings = pro.stringPropertyNames();
        for (String key : strings ) {
            System.out.println(key+"--"+pro.getProperty(key));
        }
    }

tips:文本中的數據,必須是鍵值對形式,可以使用空格、等號、冒號等符號分隔。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章