-1

I am appending a file in scala, and I want to replace the last line of the file with a new text. I know how to append to a file, but I can't figure out how to overwrite the last line.

I am appending like this:

val fw = new FileWriter("src/file.txt", true) ;
fw.write("new item");

Could anybody help?

Linda Su
  • 425
  • 1
  • 6
  • 18

1 Answers1

1

The most efficient way I can think of is the following:

  1. Read the file as a RandomAccessFile.
  2. Go to the end of the file Start reading backwards till you find the end of the last but one line.
  3. Get rid of this last line
  4. Append your line to this new file

Here is an example of how to remove the last line in Java using RandomAccessFile. Delete last line in text file

Community
  • 1
  • 1
Soumya Simanta
  • 11,523
  • 24
  • 106
  • 161
  • Basically break the whole thing into 2 steps. Step 1- get rid of the last line. Step 2 - add the line you want to add to the last line. – Soumya Simanta Dec 02 '14 at 16:40
  • Could you tell me how to delete the last line of the file in scala then? – Linda Su Dec 02 '14 at 17:19
  • This doesn't help. Long, byte don't seem to work. If you could explain a bit about RandomAccessFile? That's giving an error too! – Linda Su Dec 02 '14 at 18:30