6

如何使用 Lua 提取文件?

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

require "zip"

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

    -- iterate through each file insize the zip file
    for file in zfile:files() do
        local currFile, err = zfile:open(file.filename)
        local currFileContents = currFile:read("*a") -- read entire contents of current file
        local hBinaryOutput = io.open(destinationPath .. file.filename, "wb")

        -- write current file inside zip to a file outside zip
        if(hBinaryOutput)then
            hBinaryOutput:write(currFileContents)
            hBinaryOutput:close()
        end
    end

    zfile:close()
end
-- call the function
ExtractZipAndCopyFiles("C:\\Users\\bhannan\\Desktop\\LUA\\", "example.zip", "C:\\Users\\bhannan\\Desktop\\ZipExtractionOutput\\")

为什么每次到达终点都会崩溃?

4

3 回答 3

8

简短的回答:

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-13T18:13:53.433 回答
3

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

无论如何,正确的代码是:

require "zip"

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

-- iterate through each file insize the zip file
for file in zfile:files() do
    local currFile, err = zfile:open(file.filename)
    local currFileContents = currFile:read("*a") -- read entire contents of current file
    local hBinaryOutput = io.open(destinationPath .. file.filename, "wb")

    -- write current file inside zip to a file outside zip
    if(hBinaryOutput)then
        hBinaryOutput:write(currFileContents)
        hBinaryOutput:close()
    end
    currFile.close()
end

zfile:close()
end
于 2011-08-21T19:14:34.813 回答
2

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

示例用法:

local DEFLATE = require 'compress.deflatelua'
-- uncompress gzip file
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-11T05:14:58.827 回答