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