Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: retrieve and replace the last line in a text file

Tags:

java

file-io

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.

like image 307
David Avatar asked Jan 23 '23 07:01

David


1 Answers

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.

like image 189
Jonathan Avatar answered Feb 03 '23 08:02

Jonathan