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 ...
Marshals:
  • Campbell Ritchie
  • Paul Clapham
  • Tim Cooke
  • Jeanne Boyarsky
  • Liutauras Vilda
Sheriffs:
  • Frank Carver
  • Henry Wong
  • Ron McLeod
Saloon Keepers:
  • Tim Moores
  • Frits Walraven
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
Bartenders:
  • Al Hobbs
  • Piet Souris
  • Himai Minh
  • 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 JavaDoc:java.io.RandomAccessFile . 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.


    JavaIoFaq
     
    Check your pockets for water buffalo. You might need to use this tiny ad until locate a water buffalo:
    the value of filler advertising in 2021
    https://coderanch.com/t/730886/filler-advertising
      Bookmark Topic Watch Topic
    • New Topic