1

我正在尝试使用 zlib .net 库压缩数据。不管未压缩字符串的内容如何,​​我似乎只在 raw[] 中得到两个字节的数据。

{
    string uncompressed = "1234567890";
    byte[] data = UTF8Encoding.Default.GetBytes(uncompressed);

    MemoryStream input = new MemoryStream(data);
    MemoryStream output = new MemoryStream();
    Stream outZStream = new ZOutputStream(output,zlibConst.Z_DEFAULT_COMPRESSION);

    CopyStream(input, outZStream);

    output.Seek(0, SeekOrigin.Begin);
    byte[] raw = output.ToArray();
    string compressed = Convert.ToBase64String(raw);
}

public void CopyStream(System.IO.Stream input, System.IO.Stream output)
{
    byte[] buffer = new byte[2000];
    int len;
    while ((len = input.Read(buffer, 0, 2000)) > 0)
    {
       output.Write(buffer, 0, len);
    }
    output.Flush();
}
4

1 回答 1

3

这里的问题是 ZOutputStream 实际上是在 finish() 方法(由 Close 调用)中将一些信息写入流中。Close 方法还会关闭基本流,因此在这种情况下用处不大。

将代码更改为以下内容应该可以工作:

{
    string uncompressed = "1234567890";
    byte[] data = UTF8Encoding.Default.GetBytes(uncompressed);

    MemoryStream input = new MemoryStream(data);
    MemoryStream output = new MemoryStream();
    ZOutputStream outZStream = new ZOutputStream(output,zlibConst.Z_DEFAULT_COMPRESSION);

    CopyStream(input, outZStream);

    outZStream.finish();

    output.Seek(0, SeekOrigin.Begin);
    byte[] raw = output.ToArray();
    string compressed = Convert.ToBase64String(raw);
}

public void CopyStream(System.IO.Stream input, System.IO.Stream output)
{
    byte[] buffer = new byte[2000];
    int len;
    while ((len = input.Read(buffer, 0, 2000)) > 0)
    {
       output.Write(buffer, 0, len);
    }
    output.Flush();
}
于 2009-08-25T11:32:12.113 回答