Reputation: 13
I have a java project in which I have to save the data of each run for later use. The professor wants us to use a RandomAccessFile to do this so I have to convert the objects to bytes so they can be stored in the RAF. The major problem is that if we use Serializable he'll deduct points,so my question is:
Is there a way to convert object to byte array and viceversa without serialization?
I don't want a full code just an approach to on how to do it is appreciated.
EDIT:
Thank you all for the advice, I ended up converting the objects fields to bytes and writing that to the RAF.
Upvotes: 1
Views: 3495
Reputation: 11
Maybe xml is a good idea to represent object in text format. You can give each object an unique id and use <ref>id</ref>
to show the relationships.
Upvotes: 1
Reputation: 284796
You can write primitives and a few objects (Strings, byte arrays, and boxed primitives like Boolean and Integer which will be unboxed) directly to the RAF. If you have a larger object, break it into something RAF can accept. For example, if you have a list of strings, loop over them and write each with writeUTF. Remember that you have to read it back in, so you'll have to use some kind of headers. For example, you'll probably want to write the length of the list before the elements.
Upvotes: 1
Reputation: 85476
If you can't use Serializable
on the class, you've to find all the fields of the object using Reflection.
After that you can follow the suggestion of Matthew Flashen to write those field values to your RandomAccessFile.
Upvotes: 1