How to efficiently read only last line of the text file

前端 未结 3 382
盖世英雄少女心
盖世英雄少女心 2021-01-18 18:48

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

3条回答
  •  礼貌的吻别
    2021-01-18 19:28

        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;
    }
    

提交回复
热议问题