This discussion is archived
5 Replies Latest reply: Sep 14, 2010 1:35 PM by 3004 RSS

How to modify file in the middle?

843790 Newbie
Currently Being Moderated
Hi!

What I try to do is to modify exactly the second line of the file. Currently I try to do it with RandomAccessFile. I read the first line and then write the second one, but the problem is that some data in the third line gets erased. How to do such task?
  • 1. Re: How to modify file in the middle?
    843790 Newbie
    Currently Being Moderated
    You can't insert (easily) into a file. The normal approach to this is to create a new file with the desired content, rename the original file to some temporary name, rename the new file to the old file name and then, if there were no problems, delete the original file (obviously using it's new temporary name).
  • 2. Re: How to modify file in the middle?
    843790 Newbie
    Currently Being Moderated
    That was my first approach to the problem, but I thought it can be done - without rewriting the whole file - in a quite easy way.
  • 3. Re: How to modify file in the middle?
    3004 Newbie
    Currently Being Moderated
    elOpalo wrote:
    That was my first approach to the problem, but I thought it can be done - without rewriting the whole file - in a quite easy way.
    It is not possible to replace the Nth line in a text file without rewriting the whole file unless you a) know exactly which byte that line starts and ends on, and b) replace it with a line that has the same number of bytes.

    It is possible to replace the Nth line in a non-text file only if that file is of some format that contains metadata indicating which lines start and end at which bytes. And if you do a lot of it, you'll end up with holes and fragments that you'll eventually want to compact.

    A file system stores a files as a sequence of bytes. It knows nothing about lines.
  • 4. Re: How to modify file in the middle?
    843790 Newbie
    Currently Being Moderated
    Thanks for the exhaustive answer.
  • 5. Re: How to modify file in the middle?
    3004 Newbie
    Currently Being Moderated
    You're welcome. I'm glad it was helpful. I actually was going to add a whole lot more, but got bored halfway through typing it and gave up. :-)