java C# 互通GZIP压缩 适合压缩数字字母

Java

public static String Compress(String source) {
        byte[] bytes = source.getBytes(Charset.forName("UTF-8"));
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        try {
            GZIPOutputStream gzipOutputStream = new GZIPOutputStream(outputStream);
            gzipOutputStream.write(bytes);
            gzipOutputStream.close();
            outputStream.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return Base64.getEncoder().encodeToString(outputStream.toByteArray());
    }
    public static String Decompress(String result) {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        byte[] compressed = Base64.getDecoder().decode(result.getBytes(Charset.forName("UTF-8")));
        ByteArrayInputStream in = new ByteArrayInputStream(compressed);
        try {
            GZIPInputStream ginzip = new GZIPInputStream(in);
            byte[] buffer = new byte[1024];
            int offset = -1;
            while ((offset = ginzip.read(buffer)) != -1) {
                out.write(buffer, 0, offset);
            }
            out.close();
            ginzip.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
        return out.toString();
    }

C#

 public static string Compress(string source)
        {
            var bytes = Encoding.UTF8.GetBytes(source);
            using (var compressedStream = new MemoryStream())
            {
                using (var zipStream = new GZipStream(compressedStream, CompressionMode.Compress))
                {
                    zipStream.Write(bytes, 0, bytes.Length);
                }
                return Convert.ToBase64String(compressedStream.ToArray()) ;
            }
         
        }

        public static string Decompress(string result)
        {           
            
            var bytes = Convert.FromBase64String(result);
            using (var compressStream = new MemoryStream(bytes))
            {
                using (var zipStream = new GZipStream(compressStream, CompressionMode.Decompress))
                {
                    using (var resultStream = new MemoryStream())
                    {
                        zipStream.CopyTo(resultStream);
                   return     Encoding.UTF8.GetString(resultStream.ToArray());
                      
                    }
                }
            }
        }

你可能感兴趣的:(java C# 互通GZIP压缩 适合压缩数字字母)