Haskell:用 GZip 压缩并写入文件

问题:

在 Haskell 中,你想 gzip 压缩一个字符串并将其写入文件。

解决方案

我们将为此使用 zlib 模块。你可能需要运行

install_zlib_cabal.sh
cabal install zlib

如果你还没有这样做。

这是将字符串 foobar 写入 gzip 压缩文件 foo.gz 的代码:

gzip_compress.hs
-- GZip 压缩
import qualified Codec.Compression.GZip as GZip
-- 需要将 String 字面量转换为 ByteString
import Data.ByteString.Lazy.Char8(pack)
-- ByteString.writeFile
import qualified Data.ByteString.Lazy as ByteString

main = do
       let compressedContent = pack "foobar"
       ByteString.writeFile "foo.gz" (GZip.compress compressedContent)has

Check out similar posts by category: Haskell