Bookmark Topic Watch Topic
  • Mark post as helpful
  • send pies
  • Report post to moderator
How do I edit an existing file?
One technique is to use . We can use RandomAccessFile to read through the data. When we reach the point we wish to change, we can overwrite the existing data with the new values. It's just that simple if the new value is exactly the same length as the old value.

The random access file technique is cool but when the values are not exactly the same length it can be complex. Imagine a row of childrens blocks on your desk. If you want to insert one in the middle you could move the last one over one spot, then move the next to last over one spot and so on until you make an empty spot for the insert. Or you could pick up all the blocks from the insert point to the end and move them over one spot. You can do the same thing with seek, read and write.

Often the simplest thing to do is read the whole file, pass most of it through unchanged, change the bits you have to change and write a new file. You might process one line at a time or read the whole file into memory, modify it and write it all back out again. It is a good idea to perform the edit in the following manner:

  • read original
  • write temp
  • rename original to backup
  • rename temp to original
  • erase backup

  • That always has a safe copy of either the old and/or the new in case you crash in the middle.

      Bookmark Topic Watch Topic
    • New Topic
    Boost this thread!