我有这个:
require 'tempfile'
t = Tempfile.new('test-data')
t.open
t.sync = true
t << "apples"
t.puts "bananas"
puts "contents are [#{t.read}] (#{t.size} bytes)"
t.close
这打印:
contents are [] (14 bytes)
为什么没有实际显示内容?我在 Ruby 1.9.2 上。
我有这个:
require 'tempfile'
t = Tempfile.new('test-data')
t.open
t.sync = true
t << "apples"
t.puts "bananas"
puts "contents are [#{t.read}] (#{t.size} bytes)"
t.close
这打印:
contents are [] (14 bytes)
为什么没有实际显示内容?我在 Ruby 1.9.2 上。
问题是您正在read
文件中的当前 IO 指针处执行操作,该指针在您写入后已经位于末尾。你需要rewind
在read
. 在您的示例中:
require 'tempfile'
t = Tempfile.new('test-data')
t.open
t.sync = true
t << "apples"
t.puts "bananas"
t.rewind
puts "contents are [#{t.read}] (#{t.size} bytes)"
t.close
您可能处于流的末尾,没有更多字节了。在写入之后和阅读之前,您应该倒回文件(重新打开或寻找位置 0)。
require 'tempfile'
t = Tempfile.new('test-data')
t.open
t.sync = true
t << "apples"
t.puts "bananas"
t.seek 0
puts "contents are [#{t.read}] (#{t.size} bytes)"
t.close