Csharp/C#教程:C#到Java:Base64String,MemoryStream,GZipStream分享


C#到Java:Base64String,MemoryStream,GZipStream

我有一个在.NET中被gzip压缩的Base64字符串,我想将它转换回Java中的字符串。 我正在寻找C#语法的一些Java等价物,特别是:

这是我想要转换的方法:

public static string Decompress(string zipText) { byte[] gzipBuff = Convert.FromBase64String(zipText); using (MemoryStream memstream = new MemoryStream()) { int msgLength = BitConverter.ToInt32(gzipBuff, 0); memstream.Write(gzipBuff, 4, gzipBuff.Length - 4); byte[] buffer = new byte[msgLength]; memstream.Position = 0; using (GZipStream gzip = new GZipStream(memstream, CompressionMode.Decompress)) { gzip.Read(buffer, 0, buffer.Length); } return Encoding.UTF8.GetString(buffer); } } 

任何指针都表示赞赏。

对于Base64,你有来自Apache Commons的Base64 类 ,以及带有String并返回byte[]decodeBase64方法。

然后,您可以将生成的byte[]读入ByteArrayInputStream 。 最后,将ByteArrayInputStream传递给GZipInputStream并读取未压缩的字节。


代码看起来像这样的东西:

 public static String Decompress(String zipText) throws IOException { byte[] gzipBuff = Base64.decodeBase64(zipText); ByteArrayInputStream memstream = new ByteArrayInputStream(gzipBuff); GZIPInputStream gzin = new GZIPInputStream(memstream); final int buffSize = 8192; byte[] tempBuffer = new byte[buffSize ]; ByteArrayOutputStream baos = new ByteArrayOutputStream(); while ((size = gzin.read(tempBuffer, 0, buffSize)) != -1) { baos.write(tempBuffer, 0, size); } byte[] buffer = baos.toByteArray(); baos.close(); return new String(buffer, "UTF-8"); } 

我没有测试代码,但我认为它应该可以工作,也许只需要一些修改。

对于Base64,我推荐iHolder的实现 。

GZipinputStream是解压缩GZip字节数组所需的。

ByteArrayOutputStream用于将字节写入内存。 然后,您获取字节并将它们传递给字符串对象的构造函数以进行转换,最好指定编码。

上述就是C#学习教程:C#到Java:Base64String,MemoryStream,GZipStream分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/1003848.html

(0)
上一篇 2021年12月28日
下一篇 2021年12月28日

精彩推荐