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!
baigmzAsked:
Who is Participating?
 
Mayank SAssociate Director - Product EngineeringCommented:
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.
0
 
Manikandan ThiagarajanSenior consultantCommented:
0
Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

 
Mayank SAssociate Director - Product EngineeringCommented:
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.
0
 
Manikandan ThiagarajanSenior consultantCommented:
i also posted the same comment at same time
0
 
Mayank SAssociate Director - Product EngineeringCommented:
Yes, but the one that appears first gets the points perhaps because he posted it a few seconds earlier :-)
0
 
Manikandan ThiagarajanSenior consultantCommented:
no problem
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.