Return 来自 base64 编码的 ByteArrayOutputStream 的解码字符串

Return decoded String from base64-encoded ByteArrayOutputStream

我使用 DeflaterOutputStreamByteArrayOutputStream 进行测试。

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

结果,我得到了这个 Base64 字符串:

eJzzSM3JyVcozy/KSQEAGKsEPQ==

如何从这个 Base64 字符串中再次得到“Hello world”?

要找到从 Base64 字符串返回的方法,您需要像这样“膨胀”压缩内容:

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