gd_silva
gd_silva

Reputation: 1025

Overwrite part of text file in Java

I have a Java program that I need to output to a file.

This output file has a fixed structure, let's say a header, a START line, my output, an END line and a footer.

Everytime I run my program, I want it to write the output between those START-END parts. And if there's some text, I want to overwrite it.

By now, I'm reading line by line until I detect the START line, then I write my output. There's an "END" line after my output, as I said before.

My doubt is how can I overwrite the text between START and END (the older output) for every execution (the new output).

Upvotes: 0

Views: 289

Answers (1)

Whome
Whome

Reputation: 10400

Are you familiar with RandomAccessFile class? I assume you have a variable length of body to be written between Header+START and END+Footer markers? This means you cannot just overwrite body part and expect tailing bytes to be pushed forward.

Maybe easiest implementation is how you started implement it anyway.

  • Open RandomAccessFile access
  • Find or skip to the end of START index, remember index
  • Read bytes from the end backward until found a start of END index, bytes were put to a tailBuffer while reading backward (is backward ordered due to a reversed read-write)
  • seek position back to STARTIndex+1 and write new body bytes to the end of start block
  • call raf.setLength(startLen+bodylen+endLen) to trim or extend a new file length accordingly
  • write tailBuffer to the end of file, make sure write is reversed in a proper order

This could be one way to implement this, or just read everything to RAM find indexes, overwite file with new content. This is fine if RAM is not an issue.

Upvotes: 1

Related Questions