This week's book giveaway is in the Open Source forum.
We're giving away four copies of Programmers Guide to Apache Thrift and have Randy Abernethy on-line!
See this thread for details.
Win a copy of Programmers Guide to Apache Thrift this week in the Open Source 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 all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Devaka Cooray
  • Knute Snortum
  • Paul Clapham
  • Tim Cooke
Sheriffs:
  • Liutauras Vilda
  • Jeanne Boyarsky
  • Bear Bibeault
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Ron McLeod
  • Piet Souris
  • Frits Walraven
Bartenders:
  • Ganesh Patekar
  • Tim Holloway
  • salvin francis
  • Mark post as helpful
  • send pies
  • 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
     
    Hey, sticks and stones baby. And maybe a wee mention of my stuff:
    ScroogeXHTML - small and flexible RTF to HTML converter library
    https://coderanch.com/t/710903/ScroogeXHTML-RTF-HTML-XHTML-converter
      Bookmark Topic Watch Topic
    • New Topic
    Boost this thread!