0
我想保存和加载矩阵的状态我的程序与功能dump
和Marshal
load
执行过程中(使用Matrix
)。我可以序列化的矩阵,并得到了〜275 KB的文件,但是当我尝试加载回为一个字符串将其反序列化为一个对象,红宝石给我只有它的开始。如何读取大文件到一个字符串
# 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 serialize array and deserialize back”
- “What's a reasonable way to read an entire text file as a single string?”
- “How to read whole file in Ruby?”
但没有人似乎有我的答案寻找。
你能以二进制方式读它?也许包含停止文件读取(EOF)的奇怪二进制数据。见例如https://stackoverflow.com/questions/130948/ruby-convert-file-to-string – knut