• GZipStream 压缩与解压数据


    简介:此类表示 GZip 数据格式,它使用无损压缩和解压缩文件的行业标准算法。这种格式包括一个检测数据损坏的循环冗余校验值。GZip 数据格式使用的算法与 DeflateStream 类的算法相同,但它可以扩展以使用其他压缩格式。这种格式可以通过不涉及专利使用权的方式轻松实现。gzip 的格式可以从 RFC 1952“GZIP file format specification 4.3(GZIP 文件格式规范 4.3)GZIP file format specification 4.3(GZIP 文件格式规范 4.3)”中获得。此类不能用于压缩大于 4 GB 的文件

                var list = new List<dataSource>();
                for (int i = 0; i < 1000; i++)
                {
                    list.Add(new dataSource { lemmaId = i.ToString(), pic = "图片问题" + i, title = $"这是第{i}条数据", url = "http://www.baidu.com" });
                }
    
                //进行压缩数据
                MemoryStream responseStream = new MemoryStream();
                using (GZipStream compressedStream = new GZipStream(responseStream, CompressionMode.Compress, true))
                {
                    MemoryStream st = new MemoryStream(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(list)));
                    Console.WriteLine($"原始数据长度为={st.Length}"+ "
    
    ");
                    byte[] buffer = new byte[st.Length];
                    int checkCounter = st.Read(buffer, 0, buffer.Length);
                    if (checkCounter != buffer.Length) throw new ApplicationException();
                    compressedStream.Write(buffer, 0, buffer.Length);
                }
                responseStream.Position = 0;
                var kk = responseStream;
                var txt = Encoding.UTF8.GetString(kk.ToArray());
                Console.WriteLine($"压缩后数据长度为={responseStream.Length},压缩结果为={txt}"+"
    
    ");
    
                //解压数据
                MemoryStream source = new MemoryStream();
                using (GZipStream gs = new GZipStream(kk, CompressionMode.Decompress, true))
                {
                    //从压缩流中读出所有数据
                    byte[] bytes = new byte[4096];
                    int n;
                    while ((n = gs.Read(bytes, 0, bytes.Length)) != 0)
                    {
                        source.Write(bytes, 0, n);
                    }
                }
                var txt1 = Encoding.UTF8.GetString(source.ToArray());
                Console.WriteLine($"解压后数据长度为={source.Length},压缩结果为={txt1}" + "
    
    ");

    结果:

  • 相关阅读:
    Algs4-1.5.9画树
    Algs4-1.5.7实现QuickFindUF类和QuickUnionUF类
    *Algs4-1.5.6quick-union的运行时间-(未解决)
    *Algs4-1.5.5quick-find的运行时间-(未解决)
    Algs4-1.5.3使用加权quick-union算法完成练习1.5.1
    Algs4-1.5.4给出id[]和sz[]的内容与次数
    深入了解RabbitMQ工作原理及简单使用
    python 字符串、数字转换为bytes和bytes转换为字符串
    django html模板的语法
    完美的分布式监控系统——普罗米修斯
  • 原文地址:https://www.cnblogs.com/xiaoyaodijun/p/6755970.html
Copyright © 2020-2023  润新知