How to read the last line in the txt file? Are there any built-in java methods for this?
3 answers
ReversedLinesFileReader reader = new ReversedLinesFileReader(file); String line = reader.readLine(); if (line != null) { // что-то сделать }
- you simply consider the line and check for
null
, what is the meaning of this code? - Denis - @Denis ReversedLinesFileReader reads lines in a file (in the opposite direction, similar to the BufferedReader, but starting from the last line). but also on null you need to check the same to make sure you read. - Senior Pomidor
- did not pay attention, I admit) - Denis
|
The apache-commons-io library has a class for this: org.apache.commons.io.input.ReversedLinesFileReader
its implementation is based on RandomAccessFile
ReversedLinesFileReader reader = new ReversedLinesFileReader(...); String line = reader.readLine();
|
You can run through the file to the end and leave only the last line in a string variable:
BufferedReader input = new BufferedReader(new FileReader(fileName)); String last, line; while (null != (line = input.readLine())) { last = line; }
The method is not the most elegant, but it still works smartly without installing third-party libraries — it worked for 1,000,000 lines in less than 1/3 of a second (312 milliseconds).
- and if the file has 10,000,000 lines? (rhetorical question, I think you understood me) - Senior Pomidor
- @SeniorAutomator test on a file with 1.000.000 lines now showed 312 milliseconds (less than 1/3 of a second). Why, without the need to install a third-party library, if everything works so fast? - Denis
- and if 10,000 files the size of 80 GB? third-party libraries are needed in order not to write their bikes - Senior Pomidor
- @SeniorAutomator can conduct a comparative test, I would love to look at the difference in time, now there is no way to download Apache Common. - Denis
- If you already give metrics, then why don't you write the average length of a line in a file? the parameters of your car ?, the jvm version?
|