尝试阅读压缩文件时ENOENT

时间:2017-01-23 12:41:54

标签: ruby rubyzip

我正在编写一个简单的程序,它接受一个输入字符串,将其拆分为单词并将其保存在内存中。有三种方法 - 将字符串保存到内存中,从文件加载以及从zip存档加载。这是代码:

require 'zip'

class Storage
  def initialize
    @storage = ''
  end

  def add(string)
    words = string.split ','
    words.each do |word|
      @storage << "#{word},"
    end
  end

  def load_from_file(filename)
    File.open filename, 'r' do |f|
      f.each { |line| add line }
    end
  end

  def load_from_zip(filename)
    Zip::File.open "#{filename}.zip" do |zipfile|
      zipfile.each { |entry| load_from_file entry.to_s }
    end
  end
end

虽然addload_from_file方法完全符合我的预期,但load_from_zip每次尝试运行时都会返回以下错误:

storage.rb:39:in `initialize': No such file or directory @ rb_sysopen - test.txt (Errno::ENOENT)

虽然该档案存在于我的档案中。我很感激任何关于我做错的建议

1 个答案:

答案 0 :(得分:1)

Zip::File.open "#{filename}.zip"

不提取zip文件,它只是打开它并显示内部的内容。 你不能打电话

File.open filename, 'r'

因为filename不在您的文件系统中,只是在.zip文件中。

您需要添加新方法:

require 'zip'

class Storage
  def initialize
    @storage = ''
  end

  def add(string)
    words = string.split ','
    words.each do |word|
      @storage << "#{word},"
    end
  end

  def load_from_file(filename)
    File.open filename, 'r' do |f|
      f.each { |line| add line }
    end
  end

  def load_from_zip(filename)
    Zip::File.open "#{filename}.zip" do |zipfile|
      zipfile.each { |entry| load_from_zipped_file(zipfile,entry)}
    end
  end

  private

  def load_from_zipped_file(zipfile, entry)
    zipfile.read(entry).lines.each do |line|
      add line
    end
  end
end

s = Storage.new
s.load_from_zip('test')