amend a file : Java Glossary
- amend a file
There are a number of ways to change the bytes in a file. Here is how to do it,
ordered from most to least common.
- Read the old file copying to a new file. When you get to the part that should
be changed, write new data instead. Then continue copying. When you are done, close
both files, delete the old file and rename the new file to the old, Alternatively
rename the old file to *.bak or keep both the old and new
files. HunkIO. createTempFile helps
by creating the temp file in the same directory as the old file where it can be
most easily renamed.
- You can use the HunkIO. readEntireFile approach and read the whole file into
RAM (Random Access Memory), fix it and write it out again in a single I/O.
- You can use the append option of FileOutputStream to tack a stream onto the end of an existing
- You can use RandomAccessFile to patch a few bytes. This technique does not work
well when you want to change the length of a chunk of data in the middle of a
file. You must leave room for growth when you create the file, or invent some
complicated internal file structure the way an SQL engine does to allow records to grow and shrink. If you wanted
roll you own, you could implement a hermit crab file. RandomAccessFile is tricky since you have to compute all your own