-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
  • 365
  • 1
  • 3
  • 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,173
  • 23
  • 101
  • 157