The examples in this article describe how file reads are commonly used in go language. Share to everyone for your reference. The specific analysis is as follows:
Golang a lot of file reading methods, just started when not know how to choose, so posted here immediately after the quick check.
One-time read
Small files recommend a one-time read, which makes the program simpler and faster.
Copy Code code as follows:
Func ReadAll (Filepth string) ([]byte, error) {
F, err: = OS. Open (filepth)
If Err!= nil {
return nil, err
}
Return Ioutil. ReadAll (f)
}
There are more simple ways that I often use ioutil. ReadFile (filepth)
Chunk Read
A good balance can be struck between speed and memory footprint.
Copy Code code as follows:
Package Main
Import (
"Bufio"
"IO"
"OS"
)
Func Processblock (line []byte) {
Os. Stdout.write (line)
}
Func Readblock (filepth string, bufsize int, hookfn func ([]byte)) Error {
F, err: = OS. Open (filepth)
If Err!= nil {
return err
}
Defer F.close ()
BUF: = Make ([]byte, bufsize)//Read how many bytes at a time
BFRD: = Bufio. Newreader (f)
for {
N, Err: = Bfrd.read (BUF)
HOOKFN (Buf[:n])//n is the number of bytes read successfully
If Err!= nil {//returns immediately with any errors and ignores EOF error messages
If err = = Io. EOF {
return Nil
}
return err
}
}
return Nil
}
Func Main () {
Readblock ("Test.txt", 10000, Processblock)
}
Read-by-line
Line-by-row reading can be really handy, and performance may be slow, but it takes up only a tiny amount of memory.
Copy Code code as follows:
Package Main
Import (
"Bufio"
"IO"
"OS"
)
Func Processline (line []byte) {
Os. Stdout.write (line)
}
Func ReadLine (filepth string, hookfn func ([]byte)) Error {
F, err: = OS. Open (filepth)
If Err!= nil {
return err
}
Defer F.close ()
BFRD: = Bufio. Newreader (f)
for {
Line, Err: = Bfrd.readbytes (' \ n ')
HOOKFN (line)//placed in front of error handling, even if an error occurs, will also process the data that has been read.
If Err!= nil {//returns immediately with any errors and ignores EOF error messages
If err = = Io. EOF {
return Nil
}
return err
}
}
return Nil
}
Func Main () {
ReadLine ("Test.txt", Processline)
}
I hope this article will help you with your go language program.