Java 8 Base64流包装器吃最后两个字符?

时间:2016-09-26 22:01:20

标签: java java-8 base64 kryo

我有以下代码:

public static String encode(Object object)
{
    final String result;

    try (ByteArrayOutputStream bOut = new ByteArrayOutputStream();
         Output output = new Output(bOut))
    {
        KRYO.writeObject(output, object);
        output.flush();
        result = Base64.getUrlEncoder().encodeToString(bOut.toByteArray());
    } catch (IOException e)
    {
        // Do nothing, should never happen!
        throw new RuntimeException("MEGA FAIL");
    }

    return result;
}

public static String encodeTest(Object object)
{
    final String result;

    try (ByteArrayOutputStream bOut = new ByteArrayOutputStream();
         OutputStream base64Out = Base64.getUrlEncoder().wrap(bOut);
         Output output = new Output(base64Out))
    {
        KRYO.writeObject(output, object);
        output.flush();
        result = bOut.toString();
    } catch (IOException e)
    {
        // Do nothing, should never happen!
        throw new RuntimeException("MEGA FAIL");
    }

    return result;
}

测试:

String test = "asdf";
System.out.println(encode(test));
System.out.println(encodeTest(test));

给出输出(使用kryo记录器):

00:10 TRACE: [kryo] Write: asdf
00:10 TRACE: [kryo] Object graph complete.
YXNk5g==
00:10 TRACE: [kryo] Write: asdf
00:10 TRACE: [kryo] Object graph complete.
YXNk

我的代码中是否有错误?

我是否误用了包装器?

kryo中的错误(使用3.0.3和4.0.0版测试)?

1 个答案:

答案 0 :(得分:2)

根据Base64.Encoder.wrap()的文档,您需要在完成后关闭该流:

  

建议在使用后立即关闭返回的输出流,在此期间它会将所有可能的剩余字节刷新到基础输出流。

关闭编码器流后调用bOut.toString()将解决问题:

public static String encodeTest(Object object)
{
    ByteArrayOutputStream bOut = new ByteArrayOutputStream();
    try (OutputStream base64Out = Base64.getUrlEncoder().wrap(bOut);
         Output output = new Output(base64Out))
    {
        KRYO.writeObject(output, object);
    } catch (IOException e)
    {
        // Do nothing, should never happen!
        throw new RuntimeException("MEGA FAIL");
    }

    return bOut.toString();
}