Home >Java >javaTutorial >Can You Append to Existing ObjectOutputStreams in Java?

Can You Append to Existing ObjectOutputStreams in Java?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-16 20:19:17149browse

Can You Append to Existing ObjectOutputStreams in Java?

Appending to Existing Object Streams

The question arises whether it is feasible to append to an ObjectOutputStream. An attempt to append a list of objects intermittently fails while reading, resulting in a java.io.StreamCorruptedException.

The typical usage involves:

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

out.writeObject( new Stuff(stuff) );
out.close();

Subsequently, while reading:

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() );
}

Subclassing ObjectOutputStream and overriding the writeStreamHeader method provides the solution:

public class AppendingObjectOutputStream extends ObjectOutputStream {

  public AppendingObjectOutputStream(OutputStream out) throws IOException {
    super(out);
  }

  @Override
  protected void writeStreamHeader() throws IOException {
    // do not write a header, but reset:
    // this line added after another question
    // showed a problem with the original
    reset();
  }

}

Instantiate an appendable stream if the history file exists (append without a header) or an original stream if it doesn't exist (create with a header).

The above is the detailed content of Can You Append to Existing ObjectOutputStreams in Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn