Java IO流之Properties類的使用
更新時間:2024年08月22日 17:23:10 作者:路宇
這篇文章主要介紹了Java IO流之Properties類的使用方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
前言
Properties類的基本介紹

Properties類的常見方法

使用Properties類來讀取配置文件mysql.properties
mysql.properties配置文件中具體內(nèi)容如下:

/**
* 使用Properties類來讀取mysql.properties文件
*/
public class Properties02 {
public static void main(String[] args) throws IOException {
//1.創(chuàng)建Properties對象
Properties properties = new Properties();
properties.load(new FileReader("src\\mysql.properties"));
//3.把鍵值對 顯示到控制臺
properties.list(System.out);
System.out.println("--------------------")
//根據(jù)key 獲取對應(yīng)的值
String pwd = properties.getProperty("pwd");
String user = properties.getProperty("user");
System.out.println("用戶名:" + user);
System.out.println("密碼:" + pwd);
}
}結(jié)果如下:
-- listing properties --
user=root
pwd=123456
ip=192.168.100.100
--------------------
用戶名:root
密碼:123456
使用Properties類創(chuàng)建配置文件,修改配置文件內(nèi)容
具體代碼如下:
/**
* 使用Properties類 創(chuàng)建配置文件,修改配置文件內(nèi)容
*/
public class Properties03 {
public static void main(String[] args) throws IOException {
Properties properties = new Properties();
//創(chuàng)建
//1.如果該文件沒有key,就是創(chuàng)建
//2.如果改文件有key,就是修改
/*
Properties父類就是Hashtable,底層就是Hashtable 核心方法
public synchronized V put(K key, V value) {
// Make sure the value is not null
if (value == null) {
throw new NullPointerException();
}
// Makes sure the key is not already in the hashtable.
Entry<?,?> tab[] = table;
int hash = key.hashCode();
int index = (hash & 0x7FFFFFFF) % tab.length;
@SuppressWarnings("unchecked")
Entry<K,V> entry = (Entry<K,V>)tab[index];
for(; entry != null ; entry = entry.next) {
if ((entry.hash == hash) && entry.key.equals(key)) {
V old = entry.value;
entry.value = value;//如果key存在,就替換
return old;
}
}
addEntry(hash, key, value, index); //如果是新key,就添加
return null;
}
*/
properties.setProperty("charset", "utf8");
properties.setProperty("user", "湯姆");
properties.setProperty("pwd", "888");
//store()方法的第二個參數(shù),表示注釋
properties.store(new FileOutputStream("src\\mysql2.properties"), "hello");
System.out.println("保存配置文件成功!");
}
}創(chuàng)建的配置文件如下:

總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
MyBatis-Plus 分頁查詢以及自定義sql分頁的實現(xiàn)
這篇文章主要介紹了MyBatis-Plus 分頁查詢以及自定義sql分頁的實現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-08-08
IntelliJ?IDEA?2022.2.3最新激活圖文教程(親測有用永久激活)
今天給大家分享一個?IDEA?2022.2.3?的激活破解教程,全文通過文字+圖片的方式講解,手把手教你如何激活破解?IDEA,?只需要幾分鐘即可搞定,對idea2022.2.3激活碼感興趣的朋友跟隨小編一起看看吧2022-11-11
Java并發(fā)編程之synchronized底層實現(xiàn)原理分析
這篇文章主要介紹了Java并發(fā)編程之synchronized底層實現(xiàn)原理,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-02-02
mybatis if test 不為空字符串或null的解決
這篇文章主要介紹了mybatis if test 不為空字符串或null的解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-11-11

