go - 如何使文件阅读器功能更有效?
问题描述
我正在尝试这段代码:
// 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()
}
我想知道是否有更便宜的方法来获取文件的最后两行?
解决方案
扫描缓冲区时,您只能将最后两行保留在内存中。
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()
}
推荐阅读
- sorting - 找到具有最佳复杂度的数组中唯一连续增加的子序列的数量
- c# - .NET Core 类库使用 EFCore DbContext 作为 Nuget 没有找到 EFCore
- next.js - @tailwindcss/jit 在 postcss.config.js 中配置时不起作用
- date - 使用 Google Apps 脚本的日期问题
- javascript - 在json中新建数组[]并使用js推送数据
- stata - 如何在stata中列出当前目录中的目录?
- prometheus - 当我有空值时,如何计算两个 PromQL 查询之间的差异?
- android - 显示 AlertDialog 后如何定义屏幕色调/颜色?
- spring - 创建一个依赖于另一个 bean 中的枚举值的 bean
- verification - 门级验证问题