如何在golang中关闭bufio.Reader/Writer?

huangapple go评论67阅读模式
英文:

How can I close bufio.Reader/Writer in golang?

问题

我应该如何关闭bufio.Readerbufio.Writer在golang中?

func init(){
    file,_ := os.Create("result.txt")
    writer = bufio.NewWriter(file)
}

我应该关闭Writer吗?还是只需要使用file.Close()就会关闭Writer

英文:

How can I close bufio.Reader or bufio.Writer in golang?

func init(){
    file,_ := os.Create("result.txt")
    writer = bufio.NewWriter(file)
}

Should I close Writer? or just use file.Close() will make Writer close?

答案1

得分: 23

据我所知,你不能关闭bufio.Writer

你需要做的是先调用Flush()方法刷新bufio.Writer,然后再调用Close()方法关闭os.Writer

writer.Flush()
file.Close()
英文:

As far as I know, you can't close the bufio.Writer.

What you do is to Flush() the bufio.Writer and then Close() the os.Writer:

writer.Flush()
file.Close()

答案2

得分: 3

我认为以下是规范的:

func doSomething(filename string){
    file, err := os.Create(filename)
    // 检查错误
    defer file.Close()
    writer = bufio.NewWriter(file)
    defer writer.Flush()
    
    // 在这里使用 writer
}
英文:

I think the following is canonical:

func doSomething(filename string){
    file, err := os.Create(filename)
    // check err
    defer file.Close()
    writer = bufio.NewWriter(file)
    defer writer.Flush()
    
    // use writer here
}

huangapple
  • 本文由 发表于 2012年11月22日 20:20:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/13512634.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定