There are many ways to read and write files go, here we choose ioutil package
To read the file into memory
main Package Import ( " IO / ioutil " " FMT " ) FUNC main () { data, ERR: = ioutil.ReadFile ( " a.txt " ) where # is returned by a data byte slice IF ERR =! nil { FMT .Println ( " File Reading error " , ERR) } fmt.Println ( String (Data)) }
Speak binary file bind
packr
Will static files (e.g., .txt
files) into .go
a file, then, .go
the file will be directly embedded into a binary file. packer
Very intelligent, during development, you can get static files from disk rather than binary. During development, when only a static file changes, do not have to recompile.
package main import ( "fmt" "github.com/gobuffalo/packr" ) func main() { box := packr.NewBox("../a.txt") data := box.String("test.txt") fmt.Println("Contents of file:", data) }
Read the file line by line
main Package Import ( " BUFIO " " In Flag " " FMT " " log " " OS " ) FUNC main () { // fptr: = flag.String ( " fpath " , " test.txt " , " File Read from path to " ) //flag.Parse () f, ERR: = os.Open (" a.txt " ) // required because bufio is a * os.File type, so we read another way, then introduce later IF ERR! = nil { log.Fatal(err) } defer func() { if err = f.Close(); err != nil { log.Fatal(err) } }() s := bufio.NewScanner(f) for s.Scan() { fmt.Println(s.Text()) } err = s.Err() if err != nil { log.Fatal(err) } }
Block read file
When the file is very large, especially in the case of insufficient amount of RAM memory, the entire file is read into memory does not make sense. A better approach is to read the file block. This can be done using bufio package.
package main import ( "bufio" "flag" "fmt" "log" "os" ) func main() { //fptr := flag.String("fpath", "test.txt", "file path to read from") //flag.Parse() f, err := os.Open("a.txt") if err != nil { log.Fatal(err) } defer func() { if err = f.Close(); err != nil { log.Fatal(err) } }() r := bufio.NewReader(f) b := make([]byte, 3) for { _, err := r.Read(b) if err != nil { fmt.Println("Error reading file:", err) break } fmt.Println(string(b)) } }