Rach (
[email protected]) wrote:
: Hi,
: How do I append text to the start of an existing text file? I believe the
: FileWriter only allows you to append at the end of the text file, and not at
: the start.
Well that's the meaning of append, isn't it? To put it at the beginning
you need to prepend, not append.
However, most file systems do not support this no matter what it's called,
so instead, no matter what technique you use, it involves copying all the
data in the file.
There is more than one approach you can take.
one technique is to copy the data to a new file. First copy the new data,
then append the old data. The effect is to prepend the new data, but the
result i.s in a new file (which you can rename to make it appear to be the
original
Another technique is to load the file into memory. Then manipulate the
data in memory, and then write the data back out to the original file,
over writing what was originally there.
Another technique is to make the file longer by the required amount, and
then read the file backwards starting at the old end and copying each
chunk of data to a location nearer the end. This has the advantage that
it doesn't require much memory or disk space, and if the program dies in
the middle then all the data is still in the file, (so it could be fixed
by hand if needed). It has the disadvantage that the file seeking may
make it slow,though if you read and write blocks of data then the
inefficiency is minimized.
Another technique is similar to the above except that you copy the file in
place starting at the beginning of the file. In this case you always have
to buffer a portion of the file in memory before you over write it. This
also doesn't require much memory or disk space, and the file seeks might
be more efficient cause you're starting at the beginning of the file (due
to the way the file is likely stored). If the program dies in the middle
though then you lose the part of the data buffered in memory.
Hope these descriptions make sense.