Skip to content

JAXB Marshaller count how much space it takes to write object to file before writing it to a file

I’m looking for a solution to a problem on

how to count how much space it takes to write object to file before writing it to a file

pseudo code on what I’m looking is

if (alreadyMarshalled.size() + toBeMarshalled.size() < 40 KB) {

So, I could use a counting stream from, i.e Apache CountingOutputStream, but at first I would need to know how much space would object take (tags included), however I’ve no clue how to include tags and prefixes in that count before checking to an already what was marshalled. Is there any library that would solve such a situation?



The only way to tell is to actually marshal the XML.

The idea of the CountingOutputStream is sound.

    NullOutputStream nos = new NullOutputStream();
    CountingOutputStream cos = new CountingOutputStream(nos);
    OutputStreamWriter osw = new OutputStreamWriter(cos);
    jaxbMarshaller.marshal(object, osw);
    long result = cos.getByteCount();

You have to run this twice (once to get the count, again to write it out) it’s the only deterministic way to do it, and this won’t cost you any real memory.

If you’re not worried about memory, then just dump it to a ByteArrayOutputStream, and if you decide to “keep it”, you can just dump the byte array straight in to the file without have to run through the marshaller again.

In fact with the ByteArrayOutputStream, you don’t need the CountingOutputStream, you can just find out the size of the resulting array when it’s done. But it can come at a high memory cost.

3 People found this is helpful