【问题标题】:Why does Ruby say Closed Stream IOError? [closed]为什么 Ruby 说 Closed Stream IOError? [关闭]
【发布时间】:2014-02-07 10:27:09
【问题描述】:

我的程序有问题。它说:“`write':关闭的流(IOError)”。

def backup(dir, file, time="")
    fullpath = "#{dir}/#{file}"
    #puts fullpath

        @f.puts "BKP_DATE: #{$date}"
        @f.puts "BKP_DIRECTORY: #{dir}"
        @f.puts "M_TIME: #{time}"
        @f.puts "BKP_FILE: #{file}"


        IO.readlines(fullpath).each do |line|

            @f.puts line
        end
        @f.close()

end

【问题讨论】:

  • 这里有什么问题?
  • 也许您连续两次调用backup 而没有重新打开文件@f
  • 在我的程序中,我调用了两次功能备份。 if self.backup(base, f, temps) != false puts self.backup(base, f, temps) end 他在 if 和 puts 中被调用。如果我评论 if... 我们可以暂停 Ruby 脚本吗? (例如 5 秒)。谢谢你的回答。

标签: ruby stream


【解决方案1】:

所以你的程序本质上是这样的:

f = File.open("foo.dat", "w")

f.puts "BKP_DATE: "
...
IO.readlines(fullpath).each do |line|
    f.puts line
end
f.close
f.puts "BKP_DATE: "
...
IO.readlines(fullpath).each do |line|
    f.puts line
end
f.close

您尝试close 同一个File 对象两次。

我不知道你程序的整个结构,但也许你应该在你的backup 方法中实例化File 对象。这就是你应该用 Ruby 编写它的方式(:

File.open("foo.dat", "w") {|f|
    f.puts "BKP_DATE: "
    IO.readlines(fullpath).each do |line|
        f.puts line
    end
} # f is automatically closed here

如果您确实需要在backup 方法之外打开文件,我认为您在bakcup 末尾需要的是@f.flush 而不是@f.close。如果您没有在脚本中打开数百个文件,这对您来说是一个可以接受的解决方案。

至于暂停,试试sleep 5.0

【讨论】:

猜你喜欢
  • 2015-02-03
  • 2023-03-25
  • 2011-02-01
  • 2018-11-12
  • 1970-01-01
  • 2016-08-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多