如何使文件阅读器功能更有效?

我正在尝试这段代码:


// GetFooter returns a string which is the Footer of an edi file

func GetFooter(file *os.File) (out string, err error) {

    // TODO can scanner read files backwards?  Seek can get us to the end of file 

    var lines []string

    scanner := bufio.NewScanner(file)

    for scanner.Scan() {

        lines = append(lines, scanner.Text())

    }

    line1 := lines[len(lines)-2]

    line2 := lines[len(lines)-1]


    return line1 + "\n" + line2, scanner.Err()  

}

我想知道是否有更便宜的方法来获取文件的最后两行?


月关宝盒
浏览 100回答 2
2回答

largeQ

如果您大致知道最后两行的大小,则可以设置SOME_NUMBER为该大小加上一些额外的字节以确保始终捕获最后两行,然后执行类似的操作file, err := os.Open(fileName)if err != nil {    panic(err)}defer file.Close()buf := make([]byte, SOME_NUMBER)stat, err := os.Stat(fileName)start := stat.Size() - SOME_NUMBER_, err = file.ReadAt(buf, start)if err != nil {    panic(err)}lines := strings.Split(string(start), "\n", -1)lines = lines[len(lines)-2:]

白衣染霜花

扫描缓冲区时,您只能将最后两行保留在内存中。package mainimport (&nbsp; &nbsp; "fmt"&nbsp; &nbsp; "bufio"&nbsp; &nbsp; "bytes"&nbsp; &nbsp; "strconv")func main() {&nbsp; &nbsp; var buffer bytes.Buffer&nbsp; &nbsp; for i := 0; i < 1000; i++ {&nbsp; &nbsp; &nbsp; &nbsp; s := strconv.Itoa(i)&nbsp; &nbsp; &nbsp; &nbsp; buffer.WriteString(s + "\n")&nbsp; &nbsp; }&nbsp; &nbsp;&nbsp; &nbsp; fmt.Println(GetFooter(&buffer))}func GetFooter(file *bytes.Buffer) (out string, err error) {&nbsp; &nbsp; var line1, line2 string&nbsp; &nbsp; scanner := bufio.NewScanner(file)&nbsp; &nbsp; for scanner.Scan() {&nbsp; &nbsp; &nbsp; &nbsp; line1, line2 = line2, scanner.Text()&nbsp; &nbsp; }&nbsp; &nbsp; return line1 + "\n" + line2, scanner.Err()&nbsp;&nbsp;}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go