我有一个在 .NET 中压缩的 Base64 字符串,我想将其转换回 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 http://commons.apache.org/codec/apidocs/org/apache/commons/codec/binary/Base64.html来自 Apache Commons,以及decodeBase64
方法需要一个String
并返回一个byte[]
.
然后,您可以读取结果byte[]
into a ByteArrayInputStream http://java.sun.com/javase/6/docs/api/java/io/ByteArrayInputStream.html。最后,通过ByteArrayInputStream
to a GZip输入流 http://www.j2ee.me/javase/6/docs/api/java/util/zip/GZIPInputStream.html并读取未压缩的字节。
代码看起来像这样:
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");
}
我没有测试代码,但我认为它应该可以工作,也许需要一些修改。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)