• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Efficient way of writing objects to byte array.

 
Ranch Hand
Posts: 74
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
author and iconoclast
Posts: 24207
46
Mac OS X Eclipse IDE Chrome
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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 ]
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic