2010-05-13 102 views
6

如何使用Lua提取文件?如何使用Lua從zip文件中提取文件?

更新:我現在有下面的代碼,但它每次到達函數結束時崩潰,但它成功提取所有文件並將它們放在正確的位置。

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\\") 

爲什麼每次碰到碰撞時都會碰撞?

回答

7

答案很簡單:

LuaZip是用於讀取存儲的壓縮文件內文件的輕型Lua擴展庫。該API與標準的Lua I/O庫API非常相似。

使用LuaZip從檔案中讀取文件,然後使用Lua io module將它們寫入文件系統。如果您需要ANSI C不支持的文件系統操作,請查看LuaFileSystem。 LuaFileSystem是一個Lua庫,用於補充由標準Lua發行版提供的與文件系統相關的一組功能。 LuaFileSystem提供了一種可移植的方式來訪問底層的目錄結構和文件屬性。


進一步閱讀:

LAR是使用ZIP壓縮爲lua的虛擬文件系統。

如果您需要閱讀gzip流或gzipped tar files然後看看gzio。 Lua gzip文件I/O模塊模擬標準I/O模塊,但在壓縮的gzip格式文件上運行。

+0

我不相信這會奏效。我想實際提取壓縮文件內的文件,而不僅僅是查看壓縮文件內的文件。 – 2010-05-13 18:18:10

+0

提取是從檔案中讀取並寫入文件系統的過程。你需要寫入文件系統的指令嗎?如果是這樣,請參閱Lua'io'和'os'模塊。 – 2010-05-13 18:20:18

+0

所以我必須讀取和寫入每個文件?也許我會更好的做一個Windows系統調用來解壓縮文件。 – 2010-05-13 18:22:14

2

你似乎忘了在循環中關閉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 
1

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