Home >Java >javaTutorial >How Can I Append Objects to an Existing ObjectOutputStream in Java?

How Can I Append Objects to an Existing ObjectOutputStream in Java?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-20 09:06:13567browse

How Can I Append Objects to an Existing ObjectOutputStream in Java?

Appending to an ObjectOutputStream: A Solution

In Java, appending to an ObjectOutputStream is not inherently supported. Attempting to append to an existing file using the standard ObjectOutputStream will result in the StreamCorruptedException when reading.

To overcome this limitation, one can subclass ObjectOutputStream and override its writeStreamHeader method. The modified writeStreamHeader should not write a header but instead reset the stream when writing the initial object.

The following code demonstrates the creation of an AppendingObjectOutputStream class:

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

}

To utilize this class, determine if the target history file exists. If it does, instantiate the AppendingObjectOutputStream to append data without writing a header. If the file doesn't exist, instantiate the standard ObjectOutputStream to write a header.

// Check if history file exists
if (fileExists) {
  // Appendable stream
  ObjectOutputStream out = new AppendingObjectOutputStream(new FileOutputStream(filePath, true));
} else {
  // Standard stream
  ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(filePath));
}

By using the AppendingObjectOutputStream, one can successfully append objects to an existing history file, ensuring that all written objects can be read in the correct order.

The above is the detailed content of How Can I Append Objects to an Existing ObjectOutputStream 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