Properties 類簡介
Properties 類可以保存持久的屬性,這些屬性可以保存在流(Stream)裏面或者從流裏面讀取出來。每一個鍵值對的鍵或者值都是一個字符串。
Properties 類通常可以在 Java 中用於讀取配置信息,對代碼相關配置進行解耦合。配置信息通常存放於擴展名爲 .properties 的文件中。
Properties 類常用方法:
- setProperty(String key, String value)雖然 Properties 繼承了 HashTable,可以直接使用 HashTable 的 put 相關方法,但是這些方法都是泛型的,可能造成的一個後果就是存儲的鍵值對的鍵或者值都不是字符串而拋出異常。
- getProperty(String key)
- getProperty(String key, String defaultValue)
- load(InputStream inStream)從指定的輸入流中讀取屬性列表到調用的對象中去,輸入流是一個簡單的面向行的格式。
- load(Reader reader)
- loadFromXML(InputStream in)
- store(OutputStream out, String comments)將當前對象中的所有屬性列表全部以一個適當的形式全部寫進一個輸出流中,並且需要添加註釋。
- store(Writer writer, String comments)
- storeToXML(OutputStream os, String comments)
- storeToXML(OutputStream os, String comments, String encoding)
- list(PrintStream out)將當前對象中的所有屬性列表全部展示在輸出流中。
示例代碼:
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;
public class LearnProperties {
public static void main(String[] args) throws FileNotFoundException, IOException {
Properties properties = new Properties();
String path = "D:\\Property";
properties.setProperty("key1", "value1");
properties.setProperty("key2", "value2");
properties.setProperty("key3", "value3");
System.out.println(properties.getProperty("key1", "NoSuchKey"));
System.out.println(properties.getProperty("key4", "NoSuchKey"));
properties.store(new FileOutputStream(path + ".properties"), "Properties for Test");
properties.storeToXML(new FileOutputStream(path + ".xml"), "Properties for Test");
System.out.println(properties.stringPropertyNames());
properties.clear();
System.out.println(properties.stringPropertyNames());
properties.load(new FileInputStream(path + ".properties"));
System.out.println(properties.stringPropertyNames());
properties.clear();
properties.loadFromXML(new FileInputStream(path + ".xml"));
System.out.println(properties.stringPropertyNames());
}
}