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

Java 无法使Guava base64编码/解码工作,java,base64,guava,Java,Base64,Guava,似乎有一个非常愚蠢的错误,因为下面的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.getB

似乎有一个非常愚蠢的错误,因为下面的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”)


我遗漏了什么?

如果改为检查字符串是否匹配,则它确实匹配

        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]
数组(令人困惑的是)不会覆盖
对象.equals()
(类似地,它们也不会覆盖
.toString()
,这就是为什么在打印数组时会看到它们),这意味着在两个等效数组上调用
.equals()
,将不会得到预期的结果:

System.out.println(new int[]{}.equals(new int[]{}));
这将打印
false
。啊。有关更多信息,请参见有效的Java项目25:首选列表而非数组

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

System.out.println(Arrays.equals(new int[]{}, new int[]{}));
因此,请尝试使用
Arrays.equals()
或JUnit代替
Assert.assertEquals()


这应该和预期的一样。

两字节数组,即使它们包含相同的值,也不相等。有一个断言验证两个数组是否相等,但是JUnit3太旧了,我记不起方法的名称。可能类似于
assertArrayEquals()
。绝对同意这更可能是JUnit的错误用法,而不是Guava的错误用法。明确指定字符集是个好主意,这是常见的错误源。在
.getBytes()
和(如果您使用它)
newstring()
中,您应该始终显式指定字符集。该类使这变得很容易-只要使用
UTF_8
,就可以在任何需要字符集的地方使用,而且(几乎)永远不会出错。
junit.framework.Assert.assertArrayEquals(
    hello.getBytes(),
    BaseEncoding.base64().decode(BaseEncoding.base64().encode(hello.getBytes())
    )
);