http://blog.developer.tw/post/756-how-to-store-java-object-in-file

 

保存Java物件是一個實用的方法,有時候會希望程序結束再度開啟時保有上一次的狀態。例如你玩遊戲扮演某個角色(Object),你會希望離開遊戲前能保留等級、能力值...等這些數值,以便下次再玩這個遊戲能再使用這個角色。

下面的範例介紹如何保存一個物件到檔案裡(Store object in file)以及如何讀取物件(Load Object from file)

  1. 對於要保存的物件類別要實作Serializable即加入implements Serializable
classRoleimplementsSerializable{privateint level;publicString name;}
  1. 儲存物件的程式碼片段
Role role =newRole();
role.name ="JSON";try{FileOutputStream fos =newFileOutputStream("Role.dat");ObjectOutputStream oos =newObjectOutputStream(fos);
    oos.writeObject(this);
    oos.flush();
    oos.close();}catch(IOException e){
    e.printStackTrace();}
  1. 讀取物件的程式碼片段
Role role =null;try{FileInputStream fis =newFileInputStream("Role.dat");ObjectInputStream ois =newObjectInputStream(fis);
    role =(Role)ois.readObject();System.out.println(role.name);}catch(ClassNotFoundException e){
    e.printStackTrace();}catch(IOException e){
    e.printStackTrace();}

很容易就能夠做到儲存物件與讀取物件,Java會很聰明地幫您將物件相關的變數儲存/讀取。

arrow
arrow
    全站熱搜

    pcwiki 發表在 痞客邦 留言(0) 人氣()