无法使Guava base64编码/解码工作

时间:2016-05-02 19:29:56

标签: java base64 guava

似乎某个地方出现了一个非常愚蠢的错误,因为以下的hello-world计划对我不起作用。

PositioningManager.OnPositionChangedListener

我甚至尝试过import com.google.common.io.BaseEncoding; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; String hello = "hello"; junit.framework.Assert.assertEquals( hello.getBytes(), BaseEncoding.base64().decode( BaseEncoding.base64().encode(hello.getBytes()) ) );

我错过了什么?

2 个答案:

答案 0 :(得分:4)

阵列(令人困惑)不会覆盖Object.equals()(同样他们也不会覆盖.toString(),这就是为什么在打印数组时会看到useless \[Lsome.Type;@28a418fc strings的原因),这意味着在两个等效数组上调用.equals()将无法获得您期望的结果:

System.out.println(new int[]{}.equals(new int[]{}));

这会打印false。啊。请参阅有效Java项目25:首选列表到数组以获取更多信息。

相反,您应该使用Arrays类中的静态帮助函数对数组执行这些操作。例如,这会打印true

System.out.println(Arrays.equals(new int[]{}, new int[]{}));

请尝试使用Arrays.equals()或JUnit' Assert.assertArrayEquals()代替Assert.assertEquals()

junit.framework.Assert.assertArrayEquals(
    hello.getBytes(),
    BaseEncoding.base64().decode(BaseEncoding.base64().encode(hello.getBytes())
    )
);

这应该符合预期。

答案 1 :(得分:2)

如果您改为检查字符串是否匹配,那么它确实匹配。

        junit.framework.Assert.assertEquals(
            hello,
            new String(
                    BaseEncoding.base64().decode(
                            BaseEncoding.base64().encode(hello.getBytes())
                    )
            ));

你的支票看的是地址,我不知道为什么。如果您查看字节[]中的值,您会看到它们匹配。

        System.out.println("hello.getBytes = " + Arrays.toString(hello.getBytes()));
    System.out.println("decoded = " + Arrays.toString(BaseEncoding.base64().decode(
            BaseEncoding.base64().encode(hello.getBytes())
    )
    ));

输出:

hello.getBytes = [104, 101, 108, 108, 111]
decoded = [104, 101, 108, 108, 111]
相关问题