似乎有一个很愚蠢的错误,因为下面的hello-world程序对我不起作用。

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


我什至尝试了hello.getBytes("ISO-8859-1")

我想念什么?

最佳答案

数组(容易混淆)不会覆盖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())
    )
);


这应该符合预期。

关于java - 无法使Guava base64编码/解码有效,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36990210/

10-10 22:53