What is the most efficient way of retrieving and replacing the last line of a text file (in Java 1.4) that could potentially contain millions of lines? Code examples I have seen so far have needed to iterate through the entire file line-by-line before determining if the last line was reached.
A similar question was asked about replacing the first line in a text file in Java, but an adapted solution would still require traversing the entire file with a BufferedReader
to determine the last line in the file.
Use a java.io.RandomAccessFile. Have it seek to the end of the file, then jump backwards by chunks until you find the last newline in the file. Once you've found that, just replace anything that came afterwards.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With