I have an invalid XML since it does not include the expected XML declaration. I have used RandomAccessFile to insert the declaration at index 0, but I do not seem to be able to retain the already existing XML content. Here is my code:
With RandomAccessFile, you cannot insert data except at the end. For all other positions it will overwrite what's already there.
I'd say you can go two ways to solve this:
1) The easy way:
1a) Write the XML declaration to a temporary file.
1b) Copy all remaining data from the XML file to the temporary file.
1c) Delete the original file.
1d) Move (rename) the temporary file to the original one.
2) A bit more complex:
2a) Find out how many bytes the XML declaration is.
2b) Shift everything you have up by that many bytes. You'll have to ensure that you don't overwrite existing data before it's copied though.
2c) Write the XML declaration at the start.
Both have a risk that you lose your original file. With the first way, that can only happen if 1a through 1c succeed but 1d fails. Note that you'll still have the data, just in a different folder. With the second way, it can happen at basically any moment of time. You're modifying your file, and if at any time an error occurs you're file is corrupted.
Because of the impact of failures and the complexity involved, I'd simply go for the first solution.