C#からJava:Base64String、MemoryStream、GZipStream
-
05-07-2019 - |
質問
.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には、 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は、メモリにバイトを書き込むために使用するものです。次に、バイトを取得し、文字列オブジェクトのコンストラクターに渡して変換します(エンコードを指定するのが望ましい)。
所属していません StackOverflow