在磁盘上的文件中附加golang gob [英] Append to golang gob in a file on disk

查看:183
本文介绍了在磁盘上的文件中附加golang gob的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图将 gob 编码的数据作为简单的数据存储保存在磁盘上的文件中。但是,当我下次打开它时,gob编码器会忽略文件中已有的任何数据,并在发送数据之前重新发送已发送格式的定义。看到 gob.Encoder 需要一个 io.Writer ,而不是 io.ReadWriter ,这是有道理的。编码器不知道文件中的内容,因为它无法读取它。



然而,这非常低效。由于gob类型的id可能已经改变,因此每次编码器重新启动时都必须重置解码器。



这也是不必要的难以解析的,我如何继续写入包含gob数据的文件的末尾?我是否必须创建一个新文件,移动所有数据,以便gob编码器知道它已经发送了哪些类型,或者有什么方法可以告诉编码器它应该知道哪些类型或者其他方式?我需要它在软件重新启动的情况下工作。

解决方案

不可能用一些其他编码器具有的状态来重建编码器当写一个gob值流时。如果在追加值时不能使用原始编码器,那么您有几个选择:


  • 按照您的建议移动数据。 / li>
  • 使用成帧机制将多个gob流存储到单个文件中。例如,您可以使用该流的长度为每个视频流添加前缀。


I'm trying to save gob-encoded data in a file on disk as a simple datastore. However, when I open it next time the gob encoder just ignores whatever data is already in the file, and starts over sending definitions of already sent formats before sending data. Seeing that gob.Encoder takes an io.Writer, rather than an io.ReadWriter, this makes sense. The encoder has no idea what's in the file, because it cannot read from it.

This is, however, quite inefficient. It's also unnecessarily hard to parse, since you have to reset the decoder each time the encoder restarted when writing to the file, since the gob type id's might've changed.

How can I continue to write to the end of a file containing gob data? Do I have to create a new file, moving all data over so the gob encoder knows what types it already sent, or is there a way for me to tell the encoder what types it should know about already, or some other way? I need it to work across software restarts.

解决方案

It is not possible to reconstruct an Encoder with the state that some other Encoder had when writing a stream of gob values. If you cannot use the original Encoder when appending values, then you have a couple of options:

  • Move the data over as you suggest.
  • Use a framing mechanism to store multiple gob streams to the single file. For example, you can prefix each gob stream with the length of that stream.

这篇关于在磁盘上的文件中附加golang gob的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆