2014-06-19 14 views
0

我已經使用這個代碼寫的10個記錄/上一個序列化的文件對象,現在我要修改/編輯書面上的文件保持其他只記錄第六屆記錄/對象/對象相同。請告訴我該怎麼做?EDITTING一個序列化的文件

import java.io.FileNotFoundException; 
import java.io.FileOutputStream; 
import java.io.IOException; 
import java.io.ObjectOutputStream; 
import java.io.Serializable; 
import java.util.Scanner; 

public class Write {  

    public static void main(String arg[]) throws FileNotFoundException, IOException { 

     ObjectOutputStream to = new ObjectOutputStream(new FileOutputStream("file.cer")); 
     Scanner out = new Scanner(System.in); 
     String name; 
     Double age; 

     System.out.println("write NAME and AGE otherwise ctrl+z to teminate."); 
     while(out.hasNext()) { 
      name=out.nextLine(); 
      age=out.nextDouble(); 
      to.writeObject(new Data(name,age)); 
      System.out.println("write NAME and AGE otherwise ctrl+z to teminate."); 
     } 
     out.close(); 
     System.out.println("Ended"); 
    } 
} 

class Data implements Serializable { 

    String name; 
    Double age; 

    public Data(String name, Double age) { 
     this.name=name; 
     this.age=age; 
    } 
} 
+3

您必須加載所有對象並重寫它們 – MadProgrammer

+1

我可能會指出,儘管在這個階段它可能是一個靜音點,但對象序列化旨在用於對象的短期存儲,通常用於通過電線傳輸或用於RPC目的。這不是一個合適的長期存儲機制。您可以考慮使用JAXB(作爲示例) – MadProgrammer

回答

0

我不認爲有可能編輯文件中的任何特定對象。你將需要做的是,

  1. 從文件中讀取所有數據。
  2. 編輯您想要的對象。
  3. 覆蓋以前的數據。
0

我想修改的書面上的文件保持其他記錄/編輯只有6記錄/對象/對象相同。請告訴我如何做到這一點?

你不能在實踐中。序列化的流包含塊標記和數據統計和各種東西,使得它在一般是不可能的。