ruby - 在构建 zip 文件时,如何调整 RubyZip 示例以使用 File.write_buffer 而不是 File.open?
问题描述
在构建 zip 文件时,如何调整使用 File.open 的以下示例以使用 write_buffer 而不是 File.open,如下一个代码示例中给出的那样?
这是 File.open 示例:
require 'zip'
# This is a simple example which uses rubyzip to
# recursively generate a zip file from the contents of
# a specified directory. The directory itself is not
# included in the archive, rather just its contents.
#
# Usage:
# directoryToZip = "/tmp/input"
# outputFile = "/tmp/out.zip"
# zf = ZipFileGenerator.new(directoryToZip, outputFile)
# zf.write()
class ZipFileGenerator
# Initialize with the directory to zip and the location of the output archive.
def initialize(inputDir, outputFile)
@inputDir = inputDir
@outputFile = outputFile
end
# Zip the input directory.
def write()
entries = Dir.entries(@inputDir);
entries.delete(".");
entries.delete("..")
io = Zip::File.open(@outputFile, Zip::File::CREATE);
writeEntries(entries, "", io)
io.close();
end
# A helper method to make the recursion work.
private
def writeEntries(entries, path, io)
entries.each { |e|
zipFilePath = path == "" ? e : File.join(path, e)
diskFilePath = File.join(@inputDir, zipFilePath)
puts "Deflating " + diskFilePath
if File.directory?(diskFilePath)
io.mkdir(zipFilePath)
subdir =Dir.entries(diskFilePath); subdir.delete("."); subdir.delete("..")
writeEntries(subdir, zipFilePath, io)
else
io.get_output_stream(zipFilePath) { |f|
f.puts(File.open(diskFilePath, "rb").read())}
end
}
end
end
这是我希望上面的代码适应的 write_buffer 示例:
buffer = Zip::OutputStream.write_buffer do |out|
@zip_file.entries.each do |e|
unless [DOCUMENT_FILE_PATH, RELS_FILE_PATH].include?(e.name)
out.put_next_entry(e.name)
out.write e.get_input_stream.read
end
end
out.put_next_entry(DOCUMENT_FILE_PATH)
out.write xml_doc.to_xml(:indent => 0).gsub("\n","")
out.put_next_entry(RELS_FILE_PATH)
out.write rels.to_xml(:indent => 0).gsub("\n","")
end
File.open(new_path, "wb") {|f| f.write(buffer.string) }
在此先感谢您的帮助。这是我的适应尝试,但我感到迷茫。
def writeViaBuffer()
entries = Dir["#{@inputDir}/**/*"]; entries.delete("."); entries.delete("..")
buffer = Zip::OutputStream.write_buffer do |out|
entries.each do |e|
byebug
@file = nil
@data = nil
if !File.directory?(e)
@file = File.open(e, "r+b")
@data = @file.read
unless [@outputFile, @inputDir].include?(e)
out.put_next_entry(e)
out.write @data
end
@file.close
end
end
out.put_next_entry(@outputFile)
out.write xml_doc.to_xml(:indent => 0).gsub("\n","")
out.put_next_entry(@inputDir)
out.write rels.to_xml(:indent => 0).gsub("\n","")
end
File.open(new_path, "wb") {|f| f.write(buffer.string) }
end
解决方案
推荐阅读
- c++builder - 为什么 #pragma 消息在 hpp 文件中不起作用?
- javascript - 无法创建堆积条形图?
- python - 如何使用 webscraping 来抓取 Inspect elemrnt 中的数据或查看页面源
- c# - 是否可以检索委托函数数据库并执行它?
- sql - 如何列出sybase模式中的所有表?
- mysql - 如何修复mysql访问被拒绝?适用于家庭服务器但不适用于生产服务器
- macos - 在 mac os 上更新 ca 证书
- r - 使用 withProgress() 时如何动态配置 incProgress()?
- ruby-on-rails - RSpec 测试单独通过,整个套件失败
- xml - 将具有西里尔字符的数据帧写入 HDFS 正在更改编码