Java writeObject() to always overwrite existing object, never append? -
i want serialize hashtable file using objectoutputstream.writeobject()
, want writer overwrite existing object such single object exists:
fileoutputstream fout = new fileoutputstream( f); objectoutputstream writer = new objectoutputstream(fout); writer.writeobject( hashtable); writer.flush();
the hastable updated intermittently @ runtime, use helper method persist state:
private void persistobject( hashtable ht){ writer.writeobject( ht); writer.flush(); }
the problem every time call writeobject()
, new hastable appended file; there way overwrite whatever in file single object ever persisted?
if want discard file contents , start writing @ beginning of file again, can obtain it's channel , reposition content. problem is, objectstreams uses internal headers, , if want "reset" stream need account that.
just after instantiating objectoutputstream
, store initial position (writestreamheader
writes 2 shorts - consumes 4 bytes, better generic sorry) can position channel without overwriting header.
final long initialposition = fout.getchannel().position();
then, every time have write something, skip initial bytes (by positioning channel), reset stream , write object:
//java 1.7 private void persistobject(hashtable ht){ fout.getchannel().position(initialposition); fout.reset(); writer.writeobject(ht); writer.flush(); }
//java 1.6 private void persistobject(hashtable ht){ fout.getchannel().position(initialposition); fout.getchannel().truncate(initialposition); writer.writeobject(ht); writer.flush(); }
as @bgp mentioned, don't think opening / closing file introduces overhead... don't think truncating , flushing disk @ every write efficient, or keeping file streams open long periods of time practice (or safe), still quite fun hack objectoutputstream
.
Comments
Post a Comment