dpwdldgn43486 2017-02-21 13:01
浏览 93
已采纳

走。 将[] byte写入文件将导致零字节文件

I try to serialize a structured data to file. I looked through some examples and made such construction:

func (order Order) Serialize(folder string) {
    b := bytes.Buffer{}
    e := gob.NewEncoder(&b)
    err := e.Encode(order)
    if err != nil { panic(err) }

    os.MkdirAll(folder, 0777)
    file, err := os.Create(folder + order.Id)
    if err != nil {  panic(err) }
    defer file.Close()


    writer := bufio.NewWriter(file)
    n, err := writer.Write(b.Bytes())

    fmt.Println(n)

    if err != nil {
        panic(err)
    }
}

Serialize is a method serializing its object to file called by it's id property. I looked through debugger - byte buffer contains data before writing. I mean object is fully initialized. Even n variable representing quantity of written bytes is more than a thousand - the file shouldn't be empty at all. The file is created but it is totally empty. What's wrong?

  • 写回答

1条回答 默认 最新

  • dongshuxi3105 2017-02-21 13:09
    关注

    bufio.Writer (as the package name hints) uses a buffer to cache writes. If you ever use it, you must call Writer.Flush() when you're done writing to it to ensure the buffered data gets written to the underlying io.Writer.

    Also note that you can directly write to an os.File, no need to create a buffered writer "around" it. (*os.File implements io.Writer).

    Also note that you can create the gob.Encoder directly directed to the os.File, so even the bytes.Buffer is unnecessary.

    Also os.MkdirAll() may fail, check its return value.

    Also it's better to "concatenate" parts of a file path using filepath.Join() which takes care of extra / missing slashes at the end of folder names.

    And last, it would be better to signal the failure of Serialize(), e.g. with an error return value, so the caller party has the chance to examine if the operation succeeded, and act accordingly.

    So Order.Serialize() should look like this:

    func (order Order) Serialize(folder string) error {
        if err := os.MkdirAll(folder, 0777); err != nil {
            return err
        }
    
        file, err := os.Create(filepath.Join(folder, order.Id))
        if err != nil {
            return err
        }
        defer file.Close()
    
        if err := gob.NewEncoder(file).Encode(order); err != nil {
            return err
        }
    
        return nil
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog