IOError: not opened for writing | rubyzip 2.3.2



我的项目是使用zipruby,但我需要包括一个gem依赖于rubyzip。由于这两个gem会产生冲突错误,所以我决定在迁移过程中切换到rubyzip。我能够处理所有其他情况,除了我需要对zip使用加密的情况。

使用rubyzip 2.3.2

code with zipruby:

Zip::Archive.open(<zip-file-name>, Zip::CREATE) do |z|
<list-of-strings>.each_with_index do |check, i|
z.add_buffer 'r_%02d' % i, check
end
end

Zip::Archive.encrypt(<zip-file-name>, <password-string>)

我试着用:

buffer = Zip::OutputStream.write_buffer(::StringIO.new(''), Zip::TraditionalEncrypter.new(<password-string>)) do |output|
<list-of-strings>.each_with_index do |check, i|
output.put_next_entry('r_%02d' % i)
output.write(check)
end
end
File.open(<zip-file-name>, 'wb') {|f| f.write(buffer.string) }

但是对于这个新代码,代码在output.put_next_entry('r_%02d' % i)行失败,错误为IOError: not opened for writing

有人可以帮助我做错误的代码或有一个方法来修复它。

回溯:

entry.rb  304  write(...)
[GEM_ROOT]/gems/rubyzip-2.3.2/lib/zip/entry.rb:304:in `write'
entry.rb  304  <<(...)
[GEM_ROOT]/gems/rubyzip-2.3.2/lib/zip/entry.rb:304:in `<<'
entry.rb  304  write_local_entry(...)
[GEM_ROOT]/gems/rubyzip-2.3.2/lib/zip/entry.rb:304:in `write_local_entry'
output_stream.rb  148  init_next_entry(...)
[GEM_ROOT]/gems/rubyzip-2.3.2/lib/zip/output_stream.rb:148:in `init_next_entry'
output_stream.rb  105  put_next_entry(...)
[GEM_ROOT]/gems/rubyzip-2.3.2/lib/zip/output_stream.rb:105:in `put_next_entry'

找到修复。我的文件有注释# frozen_string_literal: true,这是导致这个

使用以下代码修复:

buffer = Zip::OutputStream.write_buffer(::StringIO.new((+'')), Zip::TraditionalEncrypter.new(<password-string>)) do |output|
<list-of-strings>.each_with_index do |check, i|
output.put_next_entry('r_%02d' % i)
output.write(check)
end
end
File.open(<zip-file-name>, 'wb') {|f| f.write(buffer.string) }

最新更新