首页 > 解决方案 > 如何使文件阅读器功能更有效?

问题描述

我正在尝试这段代码:

// 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()  
}

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

标签: go

解决方案


扫描缓冲区时,您只能将最后两行保留在内存中。

在 Go 操场上尝试一下。

package main

import (
    "fmt"
    "bufio"
    "bytes"
    "strconv"
)

func main() {
    var buffer bytes.Buffer
    for i := 0; i < 1000; i++ {
        s := strconv.Itoa(i)
        buffer.WriteString(s + "\n")
    }   
    fmt.Println(GetFooter(&buffer))
}

func GetFooter(file *bytes.Buffer) (out string, err error) {
    var line1, line2 string
    scanner := bufio.NewScanner(file)
    for scanner.Scan() {
        line1, line2 = line2, scanner.Text()
    }
    return line1 + "\n" + line2, scanner.Err()  
}

推荐阅读