C#到Java:Base64String,MemoryStream,GZipStream
我有一个在.NET中被gzip压缩的Base64字符串,我想将它转换回Java中的字符串。 我正在寻找C#语法的一些Java等价物,特别是:
- Convert.FromBase64String
- 的MemoryStream
- GZipStream
这是我想要转换的方法:
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用于将字节写入内存。 然后,您获取字节并将它们传递给字符串对象的构造函数以进行转换,最好指定编码。