javabase64bytearrayoutputstream

Return decoded String from base64-encoded ByteArrayOutputStream


I use DeflaterOutputStream and ByteArrayOutputStream for my test.

String a = "Hello world";
byte[] bArr = a.getBytes();

ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(bArr.length);
DeflaterOutputStream deflaterOutputStream = new DeflaterOutputStream(byteArrayOutputStream);

deflaterOutputStream.write(bArr);
deflaterOutputStream.close();

bArr = byteArrayOutputStream.toByteArray();

System.out.println("out: "+Base64.getEncoder().encodeToString(bArr));

As a result, I get this Base64 string:

eJzzSM3JyVcozy/KSQEAGKsEPQ==

How can I get "Hello world" again from this Base64 string?


Solution

  • To find the way back from your Base64 string you need to "inflate" the compressed content like this:

        String base64 = Base64.getEncoder().encodeToString(bArr); // eJzzSM3JyVcozy/KSQEAGKsEPQ==
    
        // reverse
        byte[] decodedBytes = Base64.getDecoder().decode(base64);
        ByteArrayOutputStream byteArrayOutputStream2 = new ByteArrayOutputStream();
        InflaterOutputStream inflaterOutputStream = new InflaterOutputStream(byteArrayOutputStream2);
        inflaterOutputStream.write(decodedBytes);
        inflaterOutputStream.close();
        System.out.println("out: "+ byteArrayOutputStream2.toString()); // Hello World
        byteArrayOutputStream2.close();