如何使用Lua从ZIP文件中提取文件?

如何使用 Lua 提取文件?

更新:现在我有以下代码,但每次到达函数的末尾时都会崩溃,但它成功地提取了所有文件并将它们放在正确的位置上。

require "zip"

function ExtractZipAndCopyFiles(zipPath, zipFilename, destinationPath)
    local zfile, err = zip.open(zipPath .. zipFilename)

    -- 逐个遍历 zip 文件中的每个文件
    for file in zfile:files() do
        local currFile, err = zfile:open(file.filename)
        local currFileContents = currFile:read("*a") -- 读取当前文件的全部内容
        local hBinaryOutput = io.open(destinationPath .. file.filename, "wb")

        -- 将 zip 中的当前文件写到 zip 外的文件中
        if(hBinaryOutput)then
            hBinaryOutput:write(currFileContents)
            hBinaryOutput:close()
        end
    end

    zfile:close()
end
-- 调用函数
ExtractZipAndCopyFiles("C:\\Users\\bhannan\\Desktop\\LUA\\", "example.zip", "C:\\Users\\bhannan\\Desktop\\ZipExtractionOutput\\")

为什么每次到达末尾时都会崩溃?

原文链接 https://stackoverflow.com/questions/2829175

点赞
stackoverflow用户1491
stackoverflow用户1491

短答案:

LuaZip是一个轻量级的Lua扩展库,用于读取存储在 zip 文件中的文件。其 API 与标准的 Lua I/O 库 API 非常相似。

使用 LuaZip 从存档中读取文件,然后使用Lua io 模块将其写入文件系统。如果您需要文件系统操作不支持 ANSI C,则可以查看LuaFileSystem。LuaFileSystem 是一款 Lua 库,旨在补充标准 Lua 发行版提供的与文件系统相关的功能集。LuaFileSystem 提供了一种可移植的访问底层目录结构和文件属性的方式。


进一步阅读:

LAR是使用 ZIP 压缩技术的 Lua 虚拟文件系统。

如果需要读取gzip流或经过 gzip 压缩的tar 文件,可以查看gzio。Lua gzip 文件 I/O 模块模拟标准的 I/O 模块,但是在压缩的 gzip 格式文件上操作。

2010-05-13 18:13:53
stackoverflow用户740464
stackoverflow用户740464

似乎你在循环中忘了关闭currFile。 我不确定为什么会崩溃:也许是因为一些懒散的资源管理代码或资源耗尽(你可以打开的文件数量可能有限)...

不管怎样,正确的代码是:

require "zip"

function ExtractZipAndCopyFiles(zipPath, zipFilename, destinationPath)
local zfile, err = zip.open(zipPath .. zipFilename)

-- 遍历zip文件中的每个文件
for file in zfile:files() do
    local currFile, err = zfile:open(file.filename)
    local currFileContents = currFile:read("*a") -- 读取当前文件的所有内容
    local hBinaryOutput = io.open(destinationPath .. file.filename, "wb")

    -- 将zip文件中的当前文件写入zip文件外的文件
    if(hBinaryOutput)then
        hBinaryOutput:write(currFileContents)
        hBinaryOutput:close()
    end
    currFile.close()
end

zfile:close()
end
2011-08-21 19:14:34
stackoverflow用户1210278
stackoverflow用户1210278

“davidm”在GitHub上的“lua-compress-deflatelua”存储库中,使用Lua实现了Gzip算法。链接:https://github.com/davidm/lua-compress-deflatelua(文件在lmod目录中。)

使用示例:

local DEFLATE = require 'compress.deflatelua'
-- 解压gzip文件
local fh = assert(io.open('foo.txt.gz', 'rb'))
local ofh = assert(io.open('foo.txt', 'wb'))
DEFLATE.gunzip {input=fh, output=ofh}
fh:close(); ofh:close()
2012-09-11 05:14:58