C# 到 Java:Base64String、MemoryStream、GZipStream
我有一个在 .NET 中压缩的 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);
}
}
任何指针都值得赞赏。
I have a Base64 string that's been gzipped in .NET and I would like to convert it back into a string in Java. I'm looking for some Java equivalents to the C# syntax, particularly:
- Convert.FromBase64String
- MemoryStream
- GZipStream
Here's the method I'd like to convert:
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);
}
}
Any pointers are appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
对于 Base64,您有
Base64
class,以及采用String
并返回byte[]
的decodeBase64
方法。然后,您可以将生成的
byte[]
读入ByteArrayInputStream
。最后,将 ByteArrayInputStream 传递给 GZipInputStream 并读取未压缩的字节。代码看起来像这样:
我没有测试代码,但我认为它应该可以工作,也许需要一些修改。
For Base64, you have the
Base64
class from Apache Commons, and thedecodeBase64
method which takes aString
and returns abyte[]
.Then, you can read the resulting
byte[]
into aByteArrayInputStream
. At last, pass theByteArrayInputStream
to a GZipInputStream and read the uncompressed bytes.The code looks like something along these lines:
I didn't test the code, but I think it should work, maybe with a few modifications.
对于 Base64,我推荐 iHolder 的实现。
GZipinputStream 是解压缩 GZip 字节数组需要什么。
ByteArrayOutputStream 用于将字节写入内存。然后,您获取字节并将它们传递给字符串对象的构造函数以对其进行转换,最好指定编码。
For Base64, I recommend iHolder's implementation.
GZipinputStream is what you need to decompress a GZip byte array.
ByteArrayOutputStream is what you use to write out bytes to memory. You then get the bytes and pass them to the constructor of a string object to convert them, preferably specifying the encoding.