My Application has two files:
1. An image file and
2. A Java Object that is written(persisted) to another file.
I wish to create a single file by combining these two files. And then, (later) re-create the image and the object from this single file.
So, I create a FileOutputStream and first write the image to it followed by the object.Something like:
I am able to create this new file using the above mentioned approach. The problem is in reading the file back and recreating things. I want to re-create/construct both the object and the image but the stream is corrupted.
Can I do some sort of demarcation in the file that can distinguish the image data and object data? Is there any other approach that I can use? I can't afford to save the two resources in separate files(user might delete one of them and thereby render the other useless). If nothing works out, I might save them in separate files and then zip them to get a single file.
How do you re-read the buffer? You can only use readObject if you've written the object using writeObject, which you haven't. Since you've used the regular write method, you also need to use the regular read methods. You don't know how many bytes to read though.
There are two solutions I can think of:
1) first use writeInt to write the number of bytes in the array, then write the array as usual. When reading, first read the count, then read that many bytes before using readObject to read the POJO.
2) (the easiest) use writeObject and readObject on the byte array as well. A byte is an Object after all
Paul Clapham wrote:Another possibility would be to review the reasons why you thought you needed to jam those two things into one file in the first place. It doesn't sound like a very good idea to me.
Hmm...lets say, my application does something to the image which I am "remembering" in an object. I need to save both somehow so that later, if the user opens the same image, my application renders the image plus the information stored in the object.
I could have chosen to write to a database but that is something I cannot do. Can you suggest any other solution that can help here?