[Java基础] Properties类的基本操作和介绍
引言
Java中的.properties文件是一種配置文件,主要用于表達(dá)配置信息;通俗來說,存放的數(shù)據(jù)就像是Map中的key和value的對應(yīng)關(guān)系一樣;這樣就可以通過鍵值對來對屬性進(jìn)行匹配,并且屬性列表中每個鍵及其對應(yīng)值都是一個字符串(String類型);
在Java中存在一個Properties類可以用來保存屬性集,它可以從流中加載屬性集;所以接下來我將會詳細(xì)介紹一下如何使用Properties類以及其中的常用的方法;
Properties類和和常用方法基本介紹
Properties:
中文:
Properties 類表示了一個持久的屬性集。Properties 可保存在流中或從流中加載。屬性列表中每個鍵及其對應(yīng)值都是一個字符串。
一個屬性列表可包含另一個屬性列表作為它的“默認(rèn)值”;如果未能在原有的屬性列表中搜索到屬性鍵,則搜索第二個屬性列表。
英文:
The Properties class represents a persistent set of properties. The Properties can be saved to a stream or loaded from a stream. Each key and its corresponding value in the property list is a string.
A property list can contain another property list as its “defaults”; this second property list is searched if the property key is not found in the original property list.
這里簡單列舉幾個常用的方法,接下來的操作我也將會用到這些方法;
1,String getProperty(String key)
簡介:通過key獲取value
2,void load(InputStream inStream/Reader reader)
簡介:將文件內(nèi)容讀入內(nèi)存
3,Object setProperty(String key, String value)
簡介:設(shè)置(增加)新的鍵值對
4,void store(OutputStream out / Writer writer, String comments)
簡介:將內(nèi)存中對應(yīng)內(nèi)容寫入文件
這幾個方法是比較常用的,當(dāng)然還有幾個方法沒有寫,如果需要可以在API文檔中查詢;
接下來我將會用代碼實現(xiàn)一些操作,在這里先把.properties文件放出來:
下面的代碼操作都是基于這個文件;
讀取操作
讀取操作可以通過load方法讀取文件,再通過getProperty獲取value值;
下面我用一個代碼示范:
輸出結(jié)果:
jack 18 man寫入操作
寫入操作就有點(diǎn)意思了,這里寫入分為三種情況:
這三種情況一般按需求使用,但是我感覺最常用的還是第三種(只是個人觀點(diǎn));
下面我用代碼示范一下,代碼中已有詳細(xì)注釋;
如果不太理解就記住就好了,忘記了就看看,寫多了說不定有一天就會理解了;
刪除操作
這個操作調(diào)用的remove方法,這個有點(diǎn)意思,因為你在API文檔中找不到Properties類有這個方法,那么就可以看一下源碼:
可以發(fā)現(xiàn)它實際調(diào)用了別人的remove方法,那么是誰的呢?我們再往下看:
這個其實就是ConcurrentHashMap的方法,所以這個remove方法并沒有記在Properties類中;
其實學(xué)會怎么使用就行了,這個使用也很簡單,同樣用代碼示范一下:
package io;import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.Properties;// 實現(xiàn)對.properties 文件內(nèi)容的刪除 public class PropertiesBlog03 {public void deleteProperties() throws IOException {Properties properties = new Properties();// 將文件數(shù)據(jù)加載到內(nèi)存中properties.load(new FileInputStream("blogtest.properties"));// 通過鍵值刪除對應(yīng)的數(shù)據(jù)properties.remove("gender"); // 刪除性別//重置文件中數(shù)據(jù)properties.store(new FileOutputStream("blogtest.properties"), "this is a comment");}public static void main(String[] args) throws IOException {PropertiesBlog03 propertiesBlog03 = new PropertiesBlog03();propertiesBlog03.deleteProperties();} }運(yùn)行后文件變?yōu)?#xff1a;
#this is a comment #Fri Nov 19 21:22:00 CST 2021 name=jack age=18可以看到gender鍵值對以及刪除了;
總結(jié)
這就是對Properties的一些基礎(chǔ)介紹,可能在使用時還會遇到其他問題,可以在評論區(qū)和我交流,希望這篇文章能夠給你帶來幫助!!
歡迎大家的點(diǎn)評!
總結(jié)
以上是生活随笔為你收集整理的[Java基础] Properties类的基本操作和介绍的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: [Java基础]Map集合的遍历
- 下一篇: JDBC使用详解