Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to efficiently read only last line of the text file

Tags:

c#

file

stream

Need to get just last line from big log file. What is the best way to do that?

like image 868
0x49D1 Avatar asked May 02 '12 08:05

0x49D1


People also ask

How do you read the last line of a text in Python?

readlines()[-1] to read the last line of the file. We used [-1] because the readlines() function returns all the lines in the form of a list, and this [-1] index gives us the last element of that list.

How do you find the last line of a file?

To look at the last few lines of a file, use the tail command. tail works the same way as head: type tail and the filename to see the last 10 lines of that file, or type tail -number filename to see the last number lines of the file. Try using tail to look at the last five lines of your . profile or .

Which method can be used to read a whole line of text from a text file?

The readline() method is going to read one line from the file and return that. The readlines() method will read and return a list of all of the lines in the file. An alternative to these different read methods would be to use a for loop .

How do you read the last line of a file in Java?

In Java, we can use the Apache Commons IO ReversedLinesFileReader to read the last few lines of a File .


2 Answers

You want to read the file backwards using ReverseLineReader:

How to read a text file reversely with iterator in C#

Then run .Take(1) on it.

var lines = new ReverseLineReader(filename);
var last = lines.Take(1);

You'll want to use Jon Skeet's library MiscUtil directly rather than copying/pasting the code.

like image 185
yamen Avatar answered Oct 05 '22 11:10

yamen


    String lastline="";
    String filedata;

    // Open file to read
    var fullfiledata = new FileStream(filepath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
    StreamReader sr = new StreamReader(fullfiledata);

    //long offset = sr.BaseStream.Length - ((sr.BaseStream.Length * lengthWeNeed) / 100);
    // Assuming a line doesnt have more than 500 characters, else use above formula
    long offset = sr.BaseStream.Length - 500;

    //directly move the last 500th position
    sr.BaseStream.Seek(offset, SeekOrigin.Begin);

    //From there read lines, not whole file
    while (!sr.EndOfStream)
    {
        filedata = sr.ReadLine();
        // Interate to see last line
        if (sr.Peek() == -1)
        {
            lastline = filedata;
        }
    }       

    return lastline;
}
like image 45
Jagadheesh Avatar answered Oct 05 '22 13:10

Jagadheesh