Zer*_*ool 5 c# java memorystream gzipstream gzipinputstream
我有一个在.NET中压缩过的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);
}
}
Run Code Online (Sandbox Code Playgroud)
任何指针表示赞赏。
对于Base64,您具有Apache Commons中的Base64 类,该decodeBase64方法采用a String并返回a byte[]。
然后,您可以将结果读取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");
}
Run Code Online (Sandbox Code Playgroud)
我没有测试代码,但是我认为它应该可以工作,可能需要进行一些修改。