2014-09-26 102 views
-1

目前我序列化一個ArrayList像這樣的文件:的Java序列化覆蓋現有文件

FileOutputStream fosAlarms = null; 
    ObjectOutputStream oosAlarms = null; 
    try { 
     fosAlarms = openFileOutput("alarms.ser", Context.MODE_PRIVATE); 
     oosAlarms = new ObjectOutputStream(fosAlarms); 
     oosAlarms.writeObject(alarms); 
     System.out.println("Serialisation done"); 
    } catch (FileNotFoundException ex) { 
     ex.printStackTrace(); 
    } catch (IOException ex) { 
     ex.printStackTrace(); 
    } finally { 
     if (oosAlarms != null && fosAlarms != null) { 
      try { 
       oosAlarms.close(); 
       fosAlarms.close(); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
     } 
    } 

而這按預期工作。但我希望這種方法覆蓋當前文件(如果有的話)。如果我從數組中移除一個對象並再次序列化,則移除的對象將持續存在。我該怎麼做呢?

+2

openFileOutput在做什麼? – 2014-09-26 09:47:10

+0

您已經忽略了任何相關性的唯一代碼。序列化與它無關。 – EJP 2014-09-26 10:14:22

回答

4

使用此構造函數FileOutputStream並將append設置爲false。

FileOutputStream(String, boolean)

所以...我想你需要改變一點你的方法openFileOutput