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

use*_*246 2 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.getBytes(),
    BaseEncoding.base64().decode(
            BaseEncoding.base64().encode(hello.getBytes())
    )
);
Run Code Online (Sandbox Code Playgroud)

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

我错过了什么?

dim*_*414 5

数组(令人困惑)不会覆盖Object.equals()(同样它们不会覆盖.toString(),这就是为什么您在打印数组时会看到那些无用的\[Lsome.Type;@28a418fc字符串),这意味着调用.equals()两个等效数组不会给您预期的结果:

System.out.println(new int[]{}.equals(new int[]{}));
Run Code Online (Sandbox Code Playgroud)

这打印false. 啊。有关更多信息,请参阅Effective Java Item 25:Prefer lists to arrays

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

System.out.println(Arrays.equals(new int[]{}, new int[]{}));
Run Code Online (Sandbox Code Playgroud)

所以尝试Arrays.equals()或 JUnit 的Assert.assertArrayEquals()而不是Assert.assertEquals()

junit.framework.Assert.assertArrayEquals(
    hello.getBytes(),
    BaseEncoding.base64().decode(BaseEncoding.base64().encode(hello.getBytes())
    )
);
Run Code Online (Sandbox Code Playgroud)

这应该按预期运行。