【问题标题】:How to read a large file into a string如何将大文件读入字符串
【发布时间】:2017-11-01 16:08:26
【问题描述】:

我正在尝试使用来自Marshal 的函数dumpload 在执行我的程序期间保存和加载矩阵的状态(使用Matrix)。我可以序列化矩阵并获得约 275 KB 的文件,但是当我尝试将其作为字符串加载回以将其反序列化为对象时,Ruby 只给了我它的开头。

# when I want to save
mat_dump = Marshal.dump(@mat)  # serialize object - OK
File.open('mat_save', 'w') {|f| f.write(mat_dump)}  # write String to file - OK

# somewhere else in the code
mat_dump = File.read('mat_save')  # read String from file - only reads like 5%
@mat = Marshal.load(mat_dump)  # deserialize object - "ArgumentError: marshal data too short"

我尝试更改 load 的参数,但尚未找到不会导致错误的任何内容。

如何将整个文件加载到内存中?如果我可以逐块读取文件,然后循环将其存储在字符串中然后反序列化,它也可以工作。该文件基本上只有一大行,所以我什至不能说我会逐行阅读,问题仍然存在。

我看到了一些关于这个话题的问题:

但他们似乎都没有我正在寻找的答案。

【问题讨论】:

标签: ruby serialization io


【解决方案1】:

Marshal是二进制格式,所以需要以二进制方式读写。最简单的方法是使用IO.binread/write

...
IO.binwrite('mat_save', mat_dump)
...
mat_dump = IO.binread('mat_save')
@mat = Marshal.load(mat_dump)

请记住,Marshaling 依赖于 Ruby 版本。它只是 compatible under specific circumstances 与其他 Ruby 版本。所以请记住这一点:

在正常使用中,marshaling 只能加载使用相同的主要版本号和相等或更低的次要版本号写入的数据。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-05
    • 2010-12-12
    • 1970-01-01
    相关资源
    最近更新 更多