Say, for example, I have a complex dynamically allocated structure (such as a binary tree) that needs to be written to a file made up of different sections. I would like to first write the size of the structure as a dword followed by the structure itself, however the size of the structure is only known after I have written the structure to the file. It is difficult, in this case, to pre-determine the size of the structure in memory.
Is it best to write the size as 0, then write the structure, then seek back and overwrite the size with the correct value? I don’t like that idea, though. Is there a better/proper way to do it?
Just an idea: write the data to a
ByteArrayOutputStream, after that, you should be able to callsize()to get the actual length in bytes and calltoByteArray()to get the byte buffer, that can be written to a file.Code example
This just demonstrate a sizeof emulator (which is different from the c implementation, because it calculates the size of a serialized object – the implementation for raw bytes would be slightly different).