Extracting one file from a zip archive using Haskell

Using a library zip-conduit

, I want to extract one file from a ZIP archive (for example bar/foo.txt

).

The hackage example shows how to extract all files at once. How can I extract just one file or list of files?

Note: This question was answered using Q&A style and therefore does not show any research on purpose!

+3


source to share


1 answer


In the official example, applies extractFiles

to the [FilePath]

returned fileNames

. You can simply apply it to a custom list of filenames:

import Codec.Archive.Zip (withArchive, extractFiles)
import System.Environment (getArgs)

main = do
    -- ZIP file name: First commandline arg
    zipPath:_ <- getArgs
    withArchive zipPath $
        extractFiles ["bar/foo.txt"] "."

      

This code will create a folder bar

in the current working directory and extract the file foo.txt

to the specified folder. If such a file already exists, it will be overwritten.



If you intend to extract to a custom filename (for example, you want to extract foo.txt

to the current working directory, not a folder bar

), then you need to use conduits as shown in this example:

import Codec.Archive.Zip (withArchive, sourceEntry)
import System.Environment (getArgs)
import qualified Data.Conduit.Binary as CB

main = do
    -- ZIP file name: First commandline arg
    zipPath:_ <- getArgs
    withArchive zipPath $
        sourceEntry "bar/foo.txt" $ CB.sinkFile "foo.txt"

      

CB.sinkFile

You can use any other conduit receiver instead .

+4


source







All Articles