Appending to an ObjectOutputStream
Here's the trick: subclass ObjectOutputStream
and override the writeStreamHeader
method:
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();
}
}
To use it, just check whether the history file exists or not and instantiate either this appendable stream (in case the file exists = we append = we don't want a header) or the original stream (in case the file does not exist = we need a header).
Edit
I wasn't happy with the first naming of the class. This one's better: it describes the 'what it's for' rather then the 'how it's done'
Edit
Changed the name once more, to clarify, that this stream is only for appending to an existing file. It can't be used to create a new file with object data.
Edit
Added a call to reset()
after this question showed that the original version that just overrode writeStreamHeader
to be a no-op could under some conditions create a stream that couldn't be read.
Appending to ObjectOutputStream (writing multiple objects w/o closing stream)
Calling ObjectOutputStream.reset() after writing each object will fix this.
How can I append to an existing java.io.ObjectStream?
It is actually pretty easy to do. When you are adding to an existing stream you need to use a subclass of ObjectOutStream that overrides writeStreamHeader
so that a second header is not written in the middle of the file. For example
class NoHeaderObjectOutputStream extends ObjectOutputStream {
public NoHeaderObjectOutputStream(OutputStream os) {
super(os);
}
protected void writeStreamHeader() {}
}
Then just use a standard ObjectInputStream to read the whole file.
Writing objects to file while appending
I think that the topic I created (It is solved now) is what you are looking for.
"You can't append to an existing file created with an ObjectOutputStream, at least not without effort. There is a trick somewhere about extending ObjectOutputStream and overriding the `writeStreamHeader() method so as not to write the stream header the second time (...)" - answered by EJP
Please have look for my topic here:
- Write and read multiple objects to file.
You can also check the link below
- Appending to an ObjectOutputStream
It is what you were looking for?
Append to ObjectOutputStream iteratively
Writing the two HYB
objects to the ObjectOutputStream
doesn't merge them into a single HYB
object; the ObjectOutputStream
still contains two HYB
object, of which your code reads one. If you did a second call to readObject()
, the second one would be retrieved and could be printed to the screen. So you could just wrap the readObject()
and println()
calls in a loop that reads/writes until there's nothing else to read from the stream.
Appending to a Serialization file (Java)
You are reading the same Object twice for each iteration
while ((in.readObject()) != null) { // once
TestClass testRead = (TestClass) in.readObject(); // twice
You can change your code to
Object obj;
while ((obj = in.readObject()) != null) {
TestClass testRead = (TestClass) obj;
System.out.println(testRead.username);
System.out.println(testRead.age);
System.out.println(testRead.address);
System.out.println(testRead.phone);
}
Note
To get it to work I changed to
FileOutputStream f = new FileOutputStream("C:\\temp\\test.ser", true);
ObjectOutputStream out2 = new ObjectOutputStream(f)
{
@Override
protected void writeStreamHeader() throws IOException {
System.out.println("I am called");
reset();
}
}
;
out2.writeObject(test);
out2.writeObject(test2);
out2.close();
Related Topics
Resolving Dependency Problems in Apache Spark
How to Build Jars from Intellij Properly
What Does Servletcontext.Getrealpath("/") Mean and When Should I Use It
Java - Escape String to Prevent SQL Injection
How to Do a Deep Copy of a 2D Array in Java
Get Os-Level System Information
Replacements For Deprecated Jpms Modules With Java Ee APIs
Different Ways of Loading a File as an Inputstream
Is It Safe to Use a Static Java.Sql.Connection Instance in a Multithreaded System
What Causes Javac to Issue the "Uses Unchecked or Unsafe Operations" Warning
How to Convert Jsonstring to Jsonobject in Java
How to Run a Batch File from My Java Application
Does a Lambda Expression Create an Object on the Heap Every Time It's Executed
Extends Jframe Vs. Creating It Inside the Program