“今天我們要探索另一個有趣的新話題:屬性。

“在 Java 中,通常使程序靈活且易於定制,即易於配置。”

“例如,您的程序每小時從某個目錄複製文件一次,壓縮它們,然後通過電子郵件將它們發送給您。為此,程序需要知道文件將從中獲取的目錄以及電子郵件地址它們應該發送到哪裡。此類數據通常不存儲在應用程序代碼中,而是存儲在單獨的屬性文件中。

此文件中的數據存儲為鍵值對,由等號分隔。

例子
data.properties file
directory = c:/text/downloads
email = zapp@codegym.cc

“符號的左邊是名稱(鍵),右邊是值。”

“所以這是 HashMap 的一種文本表示?”

“一般來說,是的。”

“為了方便處理此類文件,Java 有一個特殊的 Properties 類。Properties 類繼承了 Hashtable<Object,Object>。它甚至可以被認為是一個可以從文件加載自身的 Hashtable。”

“這是它的方法:”

方法 描述
void load(Reader reader) 從 Reader 對象表示的文件中加載屬性
void load(InputStream inStream) 從 InputStream 對象表示的文件中加載屬性
void loadFromXML(InputStream in) 從 XML 文件加載屬性
Object get(Object key) 返回指定鍵的值。該方法繼承自Hashtable
String getProperty(String key) 按鍵返回屬性值(字符串)。
String getProperty(String key, String defaultValue) 如果沒有這樣的鍵,則按鍵或 defaultValue 返回屬性值。
Set<String> stringPropertyNames() 返回所有鍵的列表

“換句話說,你實際上只需要執行兩個操作——將數據從某個文件加載到Properties對像中,然後使用getProperty () 方法獲取這些屬性。好吧,不要忘記你可以像這樣使用Properties對象一個哈希表。”

“這是另一個例子:”

代碼
// The file that stores our project's properties
File file = new File("c:/data.properties");

// Create a Properties object and load data from the file into it.
Properties properties = new Properties();
properties.load(new FileReader(file));

// Get property values from the Properties object
String email = properties.getProperty("email");
String directory = properties.getProperty("directory");

// Get a numeric value from the Properties object
int maxFileSize = Integer.parseInt(properties.getProperty("max.size", "10000"));

“啊。所以我們創建一個 Properties 對象,然後將一個文件傳遞給它。傳遞給 load 方法。然後我們只調用 getProperty。對嗎?”

“是的。”

“而且你還說可以當HashMap使用?什麼意思?”

“Properties類繼承了Hashtable,它和HashMap是一樣的,但是它的所有方法都是同步的。你可以像這樣簡單地將屬性文件中的所有值顯示在屏幕上:”

代碼
// Get the file with the properties
File file = new File("c:/data.properties");

// Create a Properties object and load data from the file into it.
Properties properties = new Properties();
properties.load(new FileReader(file));

// Run through all the keys and display their values on the console
for (String key : properties.stringPropertyNames())
{
 System.out.println(properties.get(key));
}

“啊。一切似乎都已經到位了。謝謝你,Rishi。我要用這個很酷的東西。”