0

I am using RandomAccessFile but writeBytes() overwrites the existing content Mostly i want to implement this without using any new temporary file at least methods name few clues or techniques will do.

tshepang
  • 12,111
  • 21
  • 91
  • 136
  • use `seek()` to move to a byte location. http://docs.oracle.com/javase/7/docs/api/java/io/RandomAccessFile.html – CMPS Jun 14 '14 at 05:43
  • You need another data structure than a text file for this to work. – Thomas Padron-McCarthy Jun 14 '14 at 06:10
  • possible duplicate of [How to insert text after a particular line of a file](http://stackoverflow.com/questions/17473303/how-to-insert-text-after-a-particular-line-of-a-file) – Raedwald Jun 14 '14 at 06:49

1 Answers1

0

To insert without the use of any temporary file, you'll have to find a way to read in and shift all subsequent lines down by one when you insert a new line. The sequential storage of lines of text poses the same kind of issues that the use of a standard array (vs. a LinkedList) does: You can't just unhook a pointer, plop in some text, and then hook up the pointer to next item to point to a subsequent line in the file. You have to perform the entire shift.

So I'd guess that you'd want to go to end of file, shift it down by a line, then move up each line and perform the same shift until you hit the position at which you want to insert the new line, at which point, you'll have cleared a space for it.

This seems very performance inefficient.

Hopefully someone knows of a better way, but this would be my approach, were a temporary file not an option.

(Alternately, you could also always just read the whole thing into a StringBuffer if it were small enough, peform the insert within that, and then write the file back out from scratch, but I imagine that you've considered that option already.)

Mer
  • 762
  • 1
  • 6
  • 12