Home >Java >javaTutorial >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(); } }
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();
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!