Win a copy of Practical SVG this week in the HTML/CSS/JavaScript forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Efficient way of writing objects to byte array.

 
Victor Ho
Ranch Hand
Posts: 74
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This might have been posted before and I am aware that many have suggested using ObjectOutputStream like below:
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(obj);
oos.flush();
oos.close();
bos.close();
byte [] data = bos.toByteArray();
Though for my case, I already have a byte[] buffer that I am sure big enough to hold the object to be written. Is there anyway I can just use this single buffer for the object?
Notice that if I follow the code above, I would have 2 outstanding buffers (ByteArrayOutputStream and my byte[] buffer) and also incur one extra copy operation copying from ByteArrayOutputStream into my byte[] buffer.
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24213
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
ByteArrayOutputStream has a protected "buf" member which is the buffer itself. I've never done this, but that member wouldn't be protected if you weren't intended to use it by subclassing. So what I'd try would be to write VincentsByteArrayOutputStream (a subclass of ByteArrayOutputStream) and give it a setByteBuffer() method, or have it take a byte[] as a constructor argument. I'd assume (of course, you should thoroughly test this assumption!) that if you set the initial buffer to be large enough, then it will never be reallocated, and all the written data will end up in the buffer you supply.
[ January 28, 2004: Message edited by: Ernest Friedman-Hill ]
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!