Win a copy of Murach's MySQL this week in the JDBC and Relational Databases forum!
    Bookmark Topic Watch Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
  • Mikalai Zaikin
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.

    With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
      Bookmark Topic Watch Topic
    • New Topic