Domanda

Ho una stringa Base64 che è stata gzipizzata in .NET e vorrei riconvertirla in una stringa in Java. Sto cercando alcuni equivalenti Java alla sintassi C #, in particolare:

  • Convert.FromBase64String
  • MemoryStream
  • GZipStream

Ecco il metodo che vorrei convertire:

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);
     }
}

Tutti i puntatori sono apprezzati.

È stato utile?

Soluzione

Per Base64, hai il Base64 class da Apache Commons e il metodo decodeBase64 che accetta un String e restituisce un byte [] .

Quindi, puoi leggere il byte [] risultante in un ByteArrayInputStream . Alla fine, passa il ByteArrayInputStream a GZipInputStream e leggi i byte non compressi.


Il codice assomiglia a qualcosa del genere:

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");
}

Non ho testato il codice, ma penso che dovrebbe funzionare, forse con alcune modifiche.

Altri suggerimenti

Per Base64, consiglio implementazione di iHolder .

GZipinputStream è ciò di cui hai bisogno per decomprimere un array di byte GZip.

ByteArrayOutputStream è ciò che si utilizza per scrivere byte in memoria. Quindi ottieni i byte e li passi al costruttore di un oggetto stringa per convertirli, preferibilmente specificando la codifica.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top