Deleting the last line of a file with Java

Sergiu picture Sergiu · Feb 5, 2012 · Viewed 8.6k times · Source

I have a .txt file, which I want to process in Java. I want to delete its last line.

I need ideas on how to achieve this without having to copy the entire content into another file and ignoring the last line. Any suggestions?

Answer

MForster picture MForster · Feb 5, 2012

You could find the beginning of the last line by scanning the file and then truncate it using FileChannel.truncate or RandomAccessFile.setLength.