问题描述
假设我们按如下方式创建文件a.txt.gz
:
Let's assume we create the file a.txt.gz
as follows:
$ echo "foobar" > a.txt
$ gzip a.txt
我打算使用 zlib-conduit
来在Haskell中模拟zcat
我正在寻找一个简单的示例,该示例也可以应用于 bzlib-conduit
.
I'm looking for a simple example that can also be applied to bzlib-conduit
.
注意:该问题以Q& A风格立即得到回答.因此,它故意不显示任何研究成果.
Note: This question was answered immediately in a Q&A-Style. Therefore it intentionally does not show any research effort.
推荐答案
如果您打算使用conduit
s,我强烈建议您阅读优秀的 Michael Snoyman的管道概述和
If you intend to work with conduit
s, I highly recommend to read the excellent Conduit overview by Michael Snoyman and the FP Complete tutorial on this topic first.
我已打开我的-vv
标志,使其适合Haskell初学者(如我自己).
I've turned on my -vv
flag to make this suitable for Haskell beginners (like myself).
您需要三件事:
- 文件源
- zlib减压过滤器
- 一个标准输出水槽
让我们从这个简单的文件复制示例开始:
Let's start off with this simple file copy example:
import Data.Conduit (runResourceT, ($$))
import qualified Data.Conduit.Binary as CB
import Data.Conduit.Zlib
main = do
runResourceT $ CB.sourceFile "input.txt" $$ CB.sinkFile "output.txt"
我们需要在此处进行哪些修改?
What do we need to modify here?
- 输入的文件名不是
a.txt.gz
- zlib解压缩器丢失
- 我们要输出到stdout,而不是
output.txt
- The input filename is not
a.txt.gz
- zlib decompressor is missing
- We want to output to stdout, not to
output.txt
实际上是 decompress
文档包含有关如何解压缩的示例.
Indeed the decompress
documentation contains an example of how to decompress.
请注意,您不能将decompress
用于gzip
生成的文件. decompress
解压缩由旧版compress
UNIX程序生成的.Z
文件.
Note that you can't use decompress
for gzip
-generated files. decompress
decompresses .Z
files generated by the old compress
UNIX program.
修改上面的示例后,我们得到:
After modifying the above example we get:
import Data.Conduit (runResourceT, ($$), ($=))
import qualified Data.Conduit.Binary as CB
import Data.Conduit.Zlib
import System.IO
main = do
runResourceT $ CB.sourceFile "a.txt.gz" $= ungzip $$ CB.sinkHandle stdout
使用bzlib-conduit
时的差异很小:
import Data.Conduit (runResourceT, ($$), ($=))
import qualified Data.Conduit.Binary as CB
import Data.Conduit.BZlib
import System.IO
main = do
runResourceT $ CB.sourceFile "a.txt.bz2" $= bunzip2 $$ CB.sinkHandle stdout
这篇关于Haskell bzlib-conduit/zlib-conduit示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!