第三次学JAVA再学不好就吃翔(part114)--Properties类
生活随笔
收集整理的這篇文章主要介紹了
第三次学JAVA再学不好就吃翔(part114)--Properties类
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
學習筆記,僅供參考,有錯必糾
文章目錄
- Properties類
- Properties類概述
- Properties類的特殊功能
- Properties的load和store功能
Properties類
Properties類概述
Properties 類表示了一個持久的屬性集;Properties 可保存在流中或從流中加載;屬性列表中每個鍵及其對應值都是一個字符串。
- 舉個例子
JAVA代碼:
package com.guiyang.restudy3;import java.util.Properties;public class D10Properties {public static void main(String[] args) {Properties properties = new Properties();properties.put("name", 123);System.out.println(properties);}}輸出:
{name=123}Properties類的特殊功能
- setProperty方法
調用Hashtable的方法put,使用 getProperty 方法提供并行性,強制要求為屬性的鍵和值使用字符串,返回值是Hashtable調用put的結果。
- getProperty方法
用指定的鍵在此屬性列表中搜索屬性,如果在此屬性列表中未找到該鍵,則接著遞歸檢查默認屬性列表及其默認值,如果未找到屬性,則此方法返回null。
- propertyNames方法
返回屬性列表中所有鍵的枚舉,如果在主屬性列表中未找到同名的鍵,則包括默認屬性列表中不同的鍵。
- 舉個例子
package com.guiyang.restudy3;import java.util.Enumeration; import java.util.Properties;public class D10Properties {public static void main(String[] args) {Properties properties = new Properties();properties.setProperty("name", "Ada");properties.setProperty("tel", "15706219084");Enumeration<String> enumeration = (Enumeration<String>) properties.propertyNames();while (enumeration.hasMoreElements()) {String key = enumeration.nextElement();String value = properties.getProperty(key);System.out.println(key + ":" + value); } } }
輸出:
name:Ada tel:15706219084Properties的load和store功能
- load方法
public void load(Reader reader)
按簡單的面向行的格式從輸入字符流中讀取屬性列表(鍵和元素對)。
public void load(InputStream inStream)
從輸入流中讀取屬性列表(鍵和元素對)。
- store方法
public void store(Writer writer, String comments)
以適合使用 load(Reader) 方法的格式,將此 Properties 表中的屬性列表(鍵和元素對)寫入輸出字符。
public void store(OutputStream out, String comments)
以適合使用 load(InputStream) 方法加載到 Properties 表中的格式,將此 Properties 表中的屬性列表(鍵和元素對)寫入輸出流。
- 舉個例子
配置文件config.properties:
qq=1033794241 name=Jack tel=15395298980 username=AdaJAVA文件:
package com.guiyang.restudy3;import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.Enumeration; import java.util.Properties;public class D10Properties {public static void main(String[] args) throws IOException {Properties properties = new Properties();properties.load(new FileInputStream("config.properties"));System.out.println(properties);System.out.println("---------");properties.setProperty("name", "Huang");properties.store(new FileOutputStream("config.properties"), "Info"); System.out.println(properties);} }輸出:
{qq=1033794241, tel=15395298980, name=Jack, username=Ada} --------- {qq=1033794241, tel=15395298980, name=Huang, username=Ada}配置文件config.properties:
#Info #Thu Aug 27 19:41:33 CST 2020 qq=1033794241 tel=15395298980 name=Huang username=Ada總結
以上是生活随笔為你收集整理的第三次学JAVA再学不好就吃翔(part114)--Properties类的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 生石灰的成分
- 下一篇: sublime快捷操作emmet语法