2012-04-09 125 views
5

我很難搞清楚這一點。這是我想要的:在Haskell中解壓縮GZip

ghci> :m +System.FileArchive.GZip -- From the "MissingH" package 
ghci> fmap decompress $ readFile "test.html.gz" 
*** Exception: test.html.gz: hGetContents: invalid argument (invalid byte sequence) 

爲什麼我會得到那個異常?

我也試過Codec.Compression.GZip.decompresszlib package,但我不能得到類型String而不是ByteString

+1

這不是一個完整的答案,但可能'readFile'試圖解碼'test.html.gz',就好像它是在你的系統編碼中的文本編碼一樣。改用二進制讀取。 – 2012-04-10 00:55:45

回答

8

ByteStringString的轉換取決於壓縮文件的字符編碼,但假設它是ASCII或Latin-1的,這應該工作:

import Codec.Compression.GZip (decompress) 
import qualified Data.ByteString.Lazy as LBS 
import Data.ByteString.Lazy.Char8 (unpack) 

readGZipFile :: FilePath -> IO String 
readGZipFile path = fmap (unpack . decompress) $ LBS.readFile path 

如果你需要一些其他編碼類似的工作UTF-8,用適當的解碼功能代替unpack,例如Data.ByteString.Lazy.UTF8.toString

當然,如果您正在解壓縮的文件不是文本文件,最好將其保存爲ByteString

+2

如果是,解壓縮然後解碼爲文本 – alternative 2012-04-10 01:23:31