前言
bufio包實現了帶緩沖的I/O,它封裝了io.Reader和io.Writer對象,然后創建了另外一種對象(Reader或Writer)實現了相同的接口,但是增加了緩沖功能。
首先來看沒有緩沖功能的Write(os包中)方法,它會將數據直接寫到文件中。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
package main import ( "os" "fmt" ) func main() { file, err := os.OpenFile( "a.txt" , os.O_CREATE|os.O_RDWR, 0666) if err != nil { fmt.Println(err) } defer file.Close() content := []byte( "hello world!" ) if _, err = file.Write(content); err != nil { fmt.Println(err) } fmt.Println( "write file successful" ) } |
接著看一個錯誤的使用帶緩沖的Write方法例子,當下面的程序執行后是看不到寫入的數據的。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
package main import ( "os" "fmt" "bufio" ) func main() { file, err := os.OpenFile( "a.txt" , os.O_CREATE|os.O_RDWR, 0666) if err != nil { fmt.Println(err) } defer file.Close() content := []byte( "hello world!" ) newWriter := bufio.NewWriter(file) if _, err = newWriter.Write(content); err != nil { fmt.Println(err) } fmt.Println( "write file successful" ) } |
為什么會在文件中看不到寫入的數據呢,我們來看看bufio中的Write方法。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
func (b *Writer) Write(p []byte) (nn int , err error){ for len(p) > b.Available() && b.err == nil { var n int if b.Buffered() == 0{ n,b.err =b.wr.Write(p) } else { n = copy(b.buf[b.n:],p) b.n+=n b.Flush() } nn+=n p=p[n:] } if b.err!=nil { return nn, b.err } n:= copy(b.buf[b.n:],p) b.n+= n nn+=n return nn,nil } |
Write方法首先會判斷寫入的數據長度是否大于設置的緩沖長度,如果小于,則會將數據copy到緩沖中;當數據長度大于緩沖長度時,如果數據特別大,則會跳過copy環節,直接寫入文件。其他情況依然先會將數據拷貝到緩沖隊列中,然后再將緩沖中的數據寫入到文件中。
所以上面的錯誤示例,只要給其添加Flush()方法,將緩存的數據寫入到文件中。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
package main import ( "os" "fmt" "bufio" ) func main() { file, err := os.OpenFile( "./a.txt" , os.O_CREATE|os.O_RDWR, 0666) if err != nil { fmt.Println(err) } defer file.Close() content := []byte( "hello world!" ) newWriter := bufio.NewWriterSize(file, 1024) if _, err = newWriter.Write(content); err != nil { fmt.Println(err) } if err = newWriter.Flush(); err != nil { fmt.Println(err) } fmt.Println( "write file successful" ) } |
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,如果有疑問大家可以留言交流,謝謝大家對服務器之家的支持。
原文鏈接:https://blog.csdn.net/benben_2015/article/details/80614230