golang bufio包中Write方法的深入講解
前言
bufio包實(shí)現(xiàn)了帶緩沖的I/O,它封裝了io.Reader和io.Writer對象,然后創(chuàng)建了另外一種對象(Reader或Writer)實(shí)現(xiàn)了相同的接口,但是增加了緩沖功能。
首先來看沒有緩沖功能的Write(os包中)方法,它會(huì)將數(shù)據(jù)直接寫到文件中。
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")
}
接著看一個(gè)錯(cuò)誤的使用帶緩沖的Write方法例子,當(dāng)下面的程序執(zhí)行后是看不到寫入的數(shù)據(jù)的。
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")
}
為什么會(huì)在文件中看不到寫入的數(shù)據(jù)呢,我們來看看bufio中的Write方法。
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方法首先會(huì)判斷寫入的數(shù)據(jù)長度是否大于設(shè)置的緩沖長度,如果小于,則會(huì)將數(shù)據(jù)copy到緩沖中;當(dāng)數(shù)據(jù)長度大于緩沖長度時(shí),如果數(shù)據(jù)特別大,則會(huì)跳過copy環(huán)節(jié),直接寫入文件。其他情況依然先會(huì)將數(shù)據(jù)拷貝到緩沖隊(duì)列中,然后再將緩沖中的數(shù)據(jù)寫入到文件中。
所以上面的錯(cuò)誤示例,只要給其添加Flush()方法,將緩存的數(shù)據(jù)寫入到文件中。
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")
}
總結(jié)
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,如果有疑問大家可以留言交流,謝謝大家對腳本之家的支持。
相關(guān)文章
golang動(dòng)態(tài)創(chuàng)建類的示例代碼
這篇文章主要介紹了golang動(dòng)態(tài)創(chuàng)建類的實(shí)例代碼,本文通過實(shí)例代碼給大家講解的非常詳細(xì),需要的朋友可以參考下2023-06-06
Golang實(shí)現(xiàn)超時(shí)退出的三種方式
這篇文章主要介紹了Golang三種方式實(shí)現(xiàn)超時(shí)退出,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-03-03
Go語言基礎(chǔ)切片的創(chuàng)建及初始化示例詳解
這篇文章主要為大家介紹了Go語言基礎(chǔ)切片的創(chuàng)建及初始化示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2021-11-11
golang 接口嵌套實(shí)現(xiàn)復(fù)用的操作
這篇文章主要介紹了golang 接口嵌套實(shí)現(xiàn)復(fù)用的操作,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-04-04
Go語言的隊(duì)列和堆棧實(shí)現(xiàn)方法
這篇文章主要介紹了Go語言的隊(duì)列和堆棧實(shí)現(xiàn)方法,涉及container/list包的使用技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下2015-02-02
Go實(shí)現(xiàn)整合Logrus實(shí)現(xiàn)日志打印
這篇文章主要介紹了Go實(shí)現(xiàn)整合Logrus實(shí)現(xiàn)日志打印,文章圍繞主題展開詳細(xì)的內(nèi)容介紹,具有一定的參考價(jià)值,需要的小伙伴可以參考一下2022-07-07

