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

How Can I Append Objects to an Existing Object File in Java?

Barbara Streisand
Release: 2024-12-14 18:43:12
Original
755 people have browsed it

How Can I Append Objects to an Existing Object File in Java?

Appending to an Existing Object File

In Java, ObjectOutputStream allows you to serialize and write objects to a file. However, by default, this stream doesn't support appending new objects to an existing file. This topic explores a solution to append data to an existing ObjectOutputStream.

To append to an existing file, the writeStreamHeader() method of ObjectOutputStream needs to be overridden to avoid writing a header. Here's a custom AppendingObjectOutputStream class that does this:

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

}
Copy after login

To use this class for appending objects to an existing file, check if the file exists before creating the stream:

FileOutputStream fos = null;
ObjectOutputStream out = null;

File file = new File(preferences.getAppDataLocation() + "history");

if (file.exists()) {
  // Append to existing file
  fos = new FileOutputStream(file, true);
  out = new AppendingObjectOutputStream(fos);
} else {
  // Create new file with header
  fos = new FileOutputStream(file);
  out = new ObjectOutputStream(fos);
}

// Append objects to the file
out.writeObject(new Stuff(stuff));
out.close();
Copy after login

For reading the appended objects, use an ObjectInputStream as usual. The StreamCorruptedException exception would no longer occur when reading objects from the file.

The above is the detailed content of How Can I Append Objects to an Existing Object File in Java?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template