ENOENT 在尝试读取压缩文件时

ENOENT while trying to read a zipped file

我正在编写一个简单的程序,它接受一个输入字符串,将其拆分为单词并将其保存在内存中。共有三种方法——将字符串保存到内存中、从文件中加载以及从 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 returns 每次尝试 运行 时都会出现以下错误:

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

尽管该文件存在于我的存档中。对于我做错了什么的任何建议,我将不胜感激

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')