Link to home
Start Free TrialLog in
Avatar of baigmz
baigmz

asked on

Updating a segment of binary file

Hello -

I have a binary file that I create using Java's output stream. The file is made up of two parts - a header (10 bytes max) that describes the file's remaining contents and then the content itself. The content represents a user's Phone Number. New phone numbers could be added towards the end of the file.

The header contains the last phone number that was added. Hence the first 10 bytes representing the header need to be updated whenever a new phone number is added in order to indicate the last number.

How can I use Java to update only the first 10 bytes (i.e., the header)?
The header is guaranteed to be only 10 bytes.

If I use Java to 'read' the first 10 bytes, then how can I 'write' these to the first - i.e, replace the first 10 bytes?

Example code will increase the points allotted for this question. Thanks in advance!
Avatar of Mayank S
Mayank S
Flag of India image

You can read the first ten bytes using this:

http://javaalmanac.com/egs/java.io/File2ByteArray.html

Keep the array in memory, modify the contents. Then read the remaining from the file into the same array. After that, you can write the updated array back to the same file using FileOutputStream.
ASKER CERTIFIED SOLUTION
Avatar of Mick Barry
Mick Barry
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
I was about to suggest RAF but it might need more code modifications ;-) anyway, if you think you're fine with it, then its an easier approach.
i also posted the same comment at same time
Yes, but the one that appears first gets the points perhaps because he posted it a few seconds earlier :-)