附加到ObjectOutputStream

附加到ObjectOutputStream

不可能追加到ObjectOutputStream?

我正试图将其添加到对象列表中。下面的片段是一个函数,每当完成作业时都会调用它。

FileOutputStream fos = new FileOutputStream
           (preferences.getAppDataLocation() + "history" , true);ObjectOutputStream out = new ObjectOutputStream(fos);
           out.writeObject( new Stuff(stuff) );out.close();

但是当我试图读它时,我只得到了文件中的第一个。然后我得到java.io.StreamCorruptedException.

去读我用的

FileInputStream fis = new FileInputStream
        ( preferences.getAppDataLocation() + "history");ObjectInputStream in = new ObjectInputStream(fis);    try{
    while(true)
        history.add((Stuff) in.readObject());}catch( Exception e ) { 
    System.out.println( e.toString() );}

我不知道会有多少个物体存在,所以我正在阅读,而没有例外。根据谷歌的说法,这是不可能的。我想知道有没有人知道办法?


aluckdog
浏览 408回答 3
3回答

弑天下

就像API说,ObjectOutputStream构造函数将序列化流头写入基础流。并且这个头只需要在文件的开头,只有一次。所以呼唤new ObjectOutputStream(fos);在FileOutputStream这将引用同一个文件多次写入标头并损坏该文件。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java