Java: extracting and replacing the last line in a text file

What is the most efficient way to get and replace the last line of a text file (in Java 1.4) that could potentially contain millions of lines? The code examples I've seen so far have been required to reprocess the entire file in turn, before determining if the last line was reached.

A similar question was asked about replacing the first line in a text file with Java , but the adapted solution would still require going through the whole file using BufferedReader to determine the last line in the file.

+4
source share
1 answer

Use java.io.RandomAccessFile. Ask him to go to the end of the file, and then bounce back in pieces until you find the last line in the file. As soon as you find it, just replace everything that came afterwards.

+9
source

All Articles