我有一个 Base64 字符串,它在 .NET 中被压缩,我想将它转换回 Java 中的字符串。我正在寻找一些与 C# 语法等效的 Java,特别是:
- Convert.FromBase64String
- 内存流
- 压缩流
这是我要转换的方法:
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,您有 Base64
class来自 Apache Commons,以及采用 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");
}
我没有测试代码,但我认为它应该可以工作,也许需要一些修改。
关于C# 到 Java : Base64String, MemoryStream、GZipStream,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1408267/