1 Properties類的作用
在我們平時寫程序的時候,有些參數是經常改變的,而這種改變不是我們預知的。比如說我們開發了一個操作數據庫的模塊,在開發的時候我們連接本地的數據庫那麼 IP ,端口號,數據庫名稱等信息並不是固定不變的,要使得這個操作數據的模塊具有通用性,那麼以上信息就不能寫死在程序裏。通常我們的做法是用配置文件來解決。 Java中有個比較重要的類Properties(Java.util.Properties),主要用於讀取Java的配置文件,在Java中,其配置文件常爲.properties文件,格式爲文本文件,文件的內容的格式是“鍵=值”的格式,文本註釋信息可以用"#"來註釋。
2 幾個重要方法
3 代碼實現
package pkgOne;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Enumeration;
import java.util.Properties;
public class LearnProperties {
private static Properties properties=new Properties();
public static void loadProperties() throws Exception{
FileInputStream fileInput=new FileInputStream("e:/123.txt");
BufferedInputStream bufferedInput=new BufferedInputStream(fileInput);
properties.load(bufferedInput);
bufferedInput.close();
fileInput.close();
}
public static String getValue(String key) {
if(properties.containsKey(key))
return properties.getProperty(key);
else {
return "";
}
}
public static void setValue(String key,String value) {
properties.setProperty(key, value);
}
public static void saveProperties() throws Exception {
FileOutputStream fileOutput=new FileOutputStream("e:/123.txt");
BufferedOutputStream out=new BufferedOutputStream(fileOutput);
properties.store(out, "存儲properties到指定文件");
out.close();
fileOutput.close();
}
public static void getAllProperties() {
Enumeration<?> enumeration=properties.propertyNames();
while (enumeration.hasMoreElements()) {
String key = (String) enumeration.nextElement();
String value=properties.getProperty(key);
System.out.println("key:"+key+",value="+value);
}
}
public static void printProperties() {
properties.list(System.out);
}
public static void clearProperties() {
properties.clear();
}
public static void main(String[] args) throws Exception{
loadProperties();
printProperties();
System.out.println(getValue("name"));
getAllProperties();
setValue("sex", "man");
getAllProperties();
saveProperties();
}
}