This is a creation in Article, where the information may have evolved or changed.
Life goes on and on go Go go!!!
Read and write files should be frequently encountered in the development process, today to share with you is in the world of Golang, how to read and write files.
Using Io/ioutil to read and write files
First recall the previous Ioutil package introduction:
Go Language Learning ioutil Pack (the path to go)
Two methods are mentioned:
Func ReadFile
funcstring) ([]byte, error)
ReadFile reads the file named by filename and returns the contents. A successful call returns err = = Nil, not err = = EOF. Because ReadFile reads the whole file, it does not treat a EOF from Read as a error to be reported.
Func WriteFile
funcstring, data []byte, perm os.FileMode) error
WriteFile writes data to a file named by filename. If The file does not exist, WriteFile creates it with permissions perm; Otherwise WriteFile truncates it before writing.
Read the file:
package mainimport ( "fmt" "io/ioutil")func main() { b, err := ioutil.ReadFile("test.log") ifnil { fmt.Print(err) } fmt.Println(b) string(b) fmt.Println(str)}
Write file:
package mainimport ( "io/ioutil")func check(e error) { ifnil { panic(e) }}func main() { d1 := []byte("hello\ngo\n") err := ioutil.WriteFile("test.txt", d1, 0644) check(err)}
Read and write files using the OS
Again, recall the previous OS package introduction:
File-related operations in the Go Language learning OS package (the path to go)
The first thing to note is the two ways to open a file:
Func Open
funcstring) (*File, error)
Open opens the named file for reading. If successful, methods on the returned file can is used for reading; The associated file descriptor has mode o_rdonly. If There is an error, it would be of type *patherror.
Read the file:
fi, err := os.Open(path) ifnil { panic(err) } defer fi.Close()
func OpenFile
Need to provide file path, open mode, file permissions
funcstringint, perm FileMode) (*File, error)
OpenFile is the generalized open call; Most users would use Open or Create instead. It opens the named file with specified flag (o_rdonly etc) and perm, (0666 etc) if applicable. If successful, methods on the returned File can is used for I/O. If There is an error, it would be of type *patherror.
Read the file:
package mainimport ( "log" "os")func main() { f, err := os.OpenFile("notes.txt", os.O_RDWR|os.O_CREATE, 0755) ifnil { log.Fatal(err) } ifnil { log.Fatal(err) }}
Reading method
PackageMainImport("Bufio" "FMT" "IO" "Io/ioutil" "OS")funcCheck (e error) {ifE! =Nil{Panic(e)}}funcMain () {f, err: = OS. Open ("/tmp/dat") Check (ERR) B1: = Make([]byte,5) n1, Err: = F.read (B1) Check (err) fmt. Printf ("%d bytes:%s\n", N1,string(B1)) O2, err: = F.seek(6,0) Check (err) B2: = Make([]byte,2) N2, Err: = F.read (b2) Check (err) fmt. Printf ("%d bytes @%d:%s\n", N2, O2,string(B2)) O3, err: = F.seek(6,0) Check (ERR) B3: = Make([]byte,2) N3, err: = Io. Readatleast (F, B3,2) Check (err) fmt. Printf ("%d bytes @%d:%s\n", N3, O3,string(b3)) _, Err = F.seek(0,0) Check (err) R4: = Bufio. Newreader (f) B4, err: = R4. Peek(5) Check (err) fmt. Printf ("5 bytes:%s\n",string(B4)) F.close ()}
Writing method
PackageMainImport("Bufio" "FMT" "Io/ioutil" "OS")funcCheck (e error) {ifE! =Nil{Panic(e)}}funcMain () {f, err: = OS. Create ("/TMP/DAT2") Check (ERR)deferF.close () D2: = []byte{,111,109,101,Ten} n2, Err: = F.write (D2) Check (err) fmt. Printf ("wrote%d bytes\n", N2) n3, err: = F.writestring ("writes\n") FMT. Printf ("wrote%d bytes\n", N3) F.sync () W: = Bufio. Newwriter (f) N4, err: = W.writestring ("buffered\n") FMT. Printf ("wrote%d bytes\n", N4) W.flush ()}
Several methods of reading file speed comparison
PackageMainImport("Bufio" "FMT" "IO" "Io/ioutil" "OS" "Time")funcREAD0 (Pathstring)string{F, err: = Ioutil. ReadFile (PATH)ifErr! =Nil{FMT. Printf ("%s\n", err)Panic(ERR)}return string(f)}funcRead1 (Pathstring)string{fi, err: = OS. Open (PATH)ifErr! =Nil{Panic(ERR)}deferFi. Close () Chunks: = Make([]byte,1024x768,1024x768) BUF: = Make([]byte,1024x768) for{N, err: = fi. Read (BUF)ifErr! =Nil&& Err! = Io. EOF {Panic(ERR)}if0= = N { Break} chunks =Append(chunks, buf[:n] ...) }return string(chunks)}funcRead2 (Pathstring)string{fi, err: = OS. Open (PATH)ifErr! =Nil{Panic(ERR)}deferFi. Close () r: = Bufio. Newreader (FI) Chunks: = Make([]byte,1024x768,1024x768) BUF: = Make([]byte,1024x768) for{N, err: = R.read (BUF)ifErr! =Nil&& Err! = Io. EOF {Panic(ERR)}if0= = N { Break} chunks =Append(chunks, buf[:n] ...) }return string(chunks)}funcREAD3 (Pathstring)string{fi, err: = OS. Open (PATH)ifErr! =Nil{Panic(ERR)}deferFi. Close () fd, err: = Ioutil. ReadAll (FI)return string(FD)}funcMain () {file: ="Test.log"Start: = time. Now () read0 (file) T0: = time. Now () Fmt. Printf ("Cost Time%v\n", t0. Sub (start)) read1 (file) T1: = time. Now () Fmt. Printf ("Cost Time%v\n", T1. Sub (t0)) read2 (file) t2: = time. Now () Fmt. Printf ("Cost Time%v\n", T2. Sub (T1)) read3 (file) T3: = time. Now () Fmt. Printf ("Cost Time%v\n", T3. Sub (T2))}
Operation Result:
Cost Time 4.0105ms
Cost Time 11.5043ms
Cost Time 7.0042ms
Cost Time 2.4983ms
Cost Time 4.4925ms
Cost Time 11.0053ms
Cost Time 5.0082ms
Cost Time 2.9992ms
Cost Time 3.9866ms
Cost Time 15.0085ms
Cost Time 7.5054ms
Cost Time 2.5035ms
Cost Time 4.9989ms
Cost Time 14.0112ms
Cost Time 7.5045ms
Cost Time 3.508ms
Cost Time 3.0043ms
Cost Time 15.0265ms
Cost Time 8.9884ms
Cost Time 2.0036ms