Properties繼承了HashTable, 它的鍵與值都是String類型。
經常使用Properties設置/讀取系統的屬性值
package com.wkcto.chapter05.map;
import java.util.Properties;
/**
* Properties一般用來設置/讀取系統屬性值
* @author 蛙課網
*
*/
public class Test06 {
public static void main(String[] args) {
//1)創建Properties, 不需要通過泛型約束鍵與值的類型, 都是String
Properties properties = new Properties();
//2)設置屬性值
properties.setProperty("username", "wkcto");
properties.setProperty("password", "666");
//3)讀取屬性值
System.out.println( properties.getProperty("username"));
System.out.println( properties.getProperty("password"));
}
}
package com.wkcto.chapter05.map;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
/**
* 使用Properties讀取配置文件
* 1) 配置文件保存什么內容?
* 經常在配置文件中保存系統屬性
* 2) 如何添加配置文件?
* 一般情況下,會在項目中單獨創建一個包, 在該包中添加一個配置文件,配置文件的擴展名是:.properties
* 在src目錄中的.java源文件自動編譯為.class保存到bin目錄中, src目錄中的非.java源文件,Eclipse會自動復制到bin目錄中
* 3)可以使用Properties讀取配置文件內容
* @author 蛙課網
*
*/
public class Test07 {
public static void main(String[] args) throws IOException {
//1)先創建Properties
Properties properties = new Properties();
//2)加載配置文件
/*
* 把一組小狗抽象為Dog類, 把一組小貓抽象為Cat類,把一組人抽象為Person類,
* 把Dog/Cat/Person/System/String等所有的類抽象為Class類, Class類描述的是所有類的相同的特征
* 每個類都有一個class屬性,返回就是該類的Class對象, 即該類運行時類對象, 可以把運行時類對象簡單的理解為該類的字節碼文件
*/
// InputStream in = Test07.class.getResourceAsStream("/resources/config.properties");
//如果開發多線程程序,
InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream("resources/config.properties");
properties.load( in );
//3)讀取系統屬性
System.out.println( properties.getProperty("username"));
System.out.println( properties.get("password"));
}
}
resources包中的config.properties配置文件內容如下:
username=wkcto
password:147
package com.wkcto.chapter05.map;
import java.util.ResourceBundle;
/**
* 使用ResourceBundle讀取配置文件
* @author 蛙課網
*
*/
public class Test08 {
public static void main(String[] args) {
//加載配置文件時,不需要擴展名,(前提是配置文件擴展名是properties)
ResourceBundle bundle = ResourceBundle.getBundle("resources/config");
System.out.println( bundle.getString("username"));
System.out.println( bundle.getString("password"));
}
}