What I want to achieve: When I save an Integer object to a file using the writeObject()
method from ObjectOutputstream
class, I want to overwrite the old Integer object and replace it with the new one. But I don't want to close and open again the stream every time I want to put a new Integer object. I just want to update it with new values.
The solution that I come up with didn't work for me. Here is the code:
ObjectOutputStream stream1 = new ObjectOutputStream(new FileOutputStream(new File("ClientBase"), false));
stream1.writeObject(new Integer(2));
stream1.flush();
stream1.reset();
stream1.writeObject(new Integer(9));
stream1.close();
When I read this, I have two Integer objects instead of an Integer with value 9 replaced by Integer with value 2.
If I put it like this, it works.
ObjectOutputStream stream1 = new ObjectOutputStream(new FileOutputStream(new File("ClientBase"), false));
stream1.writeObject(new Integer(2));
stream1.close();
stream1 = new ObjectOutputStream(new FileOutputStream(newFile("ClientBase"), false));
stream1.writeObject(new Integer(9));
stream1.close();
My question: Am I using the reset()
method in a wrong way and is there any other way to achieve overwriting without closing/opening stream?