我怎样才能像这样 java 片段代码解压缩 c# 中的流?

How can I decompress a stream in c# like this java snippet code?

我正在尝试在 c# 中转换此 java 片段代码,但我对此有点困惑。 这是 java 代码:

我的尝试如下,但在 gis.Read 中有一些错误,因为它需要一个 char* 而不是一个 byte[] 并且出于同样的原因在 String 构造函数中。

public static String decompress(InputStream input) throws IOException 
{
    final int BUFFER_SIZE = 32;
    GZIPInputStream gis = new GZIPInputStream(input, BUFFER_SIZE);
    StringBuilder string = new StringBuilder();
    byte[] data = new byte[BUFFER_SIZE];
    int bytesRead;
    while ((bytesRead = gis.read(data)) != -1) {
        string.append(new String(data, 0, bytesRead));
    }
    gis.close();
    // is.close();
    return string.toString();
}

我希望得到一个可读的字符串。

您需要先将字节转换为字符。为此,您需要知道编码。

在您的代码中,您可以将 new String(data, 0, bytesRead) 替换为 Encoding.UTF8.GetString(data, 0, bytesRead) 来执行此操作。但是,我会稍微不同地处理这个问题。

StreamReader 是一个有用的 class,可以在 C# 中将字节读取为文本。只需将它包裹在您的 GZipStream 周围,让它发挥它的魔力。

public static string Decompress(Stream input)
{
    // note this buffer size is REALLY small. 
    // You could stick with the default buffer size of the StreamReader (1024)
    const int BUFFER_SIZE = 32;
    string result = null;
    using (var gis = new GZipStream(input, CompressionMode.Decompress, leaveOpen: true))
    using (var reader = new StreamReader(gis, Encoding.UTF8, true, BUFFER_SIZE))
    {
        result = reader.ReadToEnd();
    }

    return result;
}