在Go语言中,是否有类似于ReadLine的方法用于读取文件?

huangapple go评论90阅读模式
英文:

Is there a ReadLine equivalent for a file in Go?

问题

你可以使用ioutil.ReadFile函数来读取文本文件的内容,然后使用bytes.Split函数将内容按照换行符进行分割,最后取得第一个分割后的部分即可。这样就可以实现在不使用bufio的情况下读取文件直到遇到换行符为止。以下是示例代码:

package main

import (
	"bytes"
	"fmt"
	"io/ioutil"
)

func main() {
	filePath := "your_file_path.txt"
	content, err := ioutil.ReadFile(filePath)
	if err != nil {
		fmt.Println("读取文件失败:", err)
		return
	}

	lines := bytes.Split(content, []byte("\n"))
	if len(lines) > 0 {
		firstLine := lines[0]
		fmt.Println(string(firstLine))
	}
}

请将your_file_path.txt替换为你要读取的文件路径。这段代码会读取文件的内容,并将其按照换行符进行分割,然后输出第一行的内容。

英文:

I want to ReadBytes until "\n" for a text file, not a bufio.

Is there a way to do this without converting to a bufio?

答案1

得分: 2

有很多方法可以实现,但我建议使用bufio进行包装。但如果这对你不起作用(为什么不起作用?),你可以继续像这样逐个字节地读取:

完整的工作示例:

package main

import (
	"bufio"
	"bytes"
	"fmt"
	"io"
)

// ReadLine 从 io.Reader 中读取以 \n 分隔的一行
// 与 bufio 不同,它通过逐个字节地读取来实现,效率较低
func ReadLine(r io.Reader) (line []byte, err error) {
	b := make([]byte, 1)
	var l int
	for err == nil {
		l, err = r.Read(b)
		if l > 0 {
			if b[0] == '\n' {
				return
			}
			line = append(line, b...)
		}
	}
	return
}

var data = `Hello, world!
I will write
three lines.`

func main() {

	b := bytes.NewBufferString(data)

	for {
		line, err := ReadLine(b)
		fmt.Println("Line: ", string(line))
		if err != nil {
			return
		}
	}
}

输出:

Line:  Hello, world!
Line:  I will write
Line:  three lines.

Playground: http://play.golang.org/p/dfb0GHPpnm

英文:

There are many ways to do it, but wrapping with bufio is what I would suggest. But if that doesn't work for you (why not?), you can go ahead and read single bytes like this:

Full working example:

package main

import (
	"bytes"
	"fmt"
	"io"
)

// ReadLine reads a line delimited by \n from the io.Reader
// Unlike bufio, it does so rather inefficiently by reading one byte at a time
func ReadLine(r io.Reader) (line []byte, err error) {
	b := make([]byte, 1)
	var l int
	for err == nil {
		l, err = r.Read(b)
		if l > 0 {
			if b[0] == '\n' {
				return
			}
			line = append(line, b...)
		}
	}
	return
}

var data = `Hello, world!
I will write
three lines.`

func main() {

	b := bytes.NewBufferString(data)

	for {
		line, err := ReadLine(b)
		fmt.Println("Line: ", string(line))
		if err != nil {
			return
		}
	}
}

Output:

Line:  Hello, world!
Line:  I will write
Line:  three lines.

Playground: http://play.golang.org/p/dfb0GHPpnm

huangapple
  • 本文由 发表于 2014年4月25日 11:15:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/23283549.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定