※問題
要將系統設定的屬性儲存到磁碟上,當下次開啟系統時可以得到相同的屬性設定。
※解決方法
使用 java.util.Properties ,它繼承自 Hashtable 。使用的方式是它會以一組 key-value 來儲存資料,指定某個key它就會回傳相對應的value,也可把它當成簡易的資料庫來使用。程式碼如下:
/* properity.java
* Created on 2008/10/11
* Author Tony
*
*/import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Properties;public class properity {
public static void main(String[] args) throws Exception {
//建立Properties物件
Properties prop = new Properties();//1.儲存屬性檔
//(1)建立FileOutputStream
FileOutputStream fout = new FileOutputStream(“myProperty.dat”);
//(2)推入資料(key,value):可用key去找value
prop.put(“Author”,”Tony”);
//(3)將資料儲存進屬性檔,可設定該屬性檔的名稱
prop.store(fout, “My Property”);
//(4)關閉資料流
fout.close();//執行完上面後,會在磁碟上存入一個檔案 myProperty.dat
//內容如下:
/*
#My Property
#Sat Oct 11 01:44:19 CST 2008
Author=Tony
*///2.讀取屬性檔
//(1)建立FileInputStream
FileInputStream fin = new FileInputStream(“myProperty.dat”);
//(2)載入屬性檔案
prop.load(fin);
//(3)以key去取得value
String value = prop.getProperty(“Author”);
//(4)關閉資料流
fin.close();
//(5)顯示資料
System.out.println(“Author: ” + value);}
}
0 回應 to “Properity – 屬性檔”