无法使Guava base64编码/解码有效 [英] Unable to make Guava base64 encode/decode work
问题描述
由于下面的hello-world程序对我不起作用,因此某处似乎存在一个非常愚蠢的错误.
It seems there is a very silly mistake somewhere as the following hello-world program is not working for me.
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()
,这就是为什么您看到那些
Arrays (confusingly) do not override Object.equals()
(similarly they don't override .toString()
, which is why you see those useless \[Lsome.Type;@28a418fc
strings when you print an array), meaning that calling .equals()
on two equivalent arrays will not give you the result you'd expect:
System.out.println(new int[]{}.equals(new int[]{}));
这将打印false
.啊.有关更多信息,请参见有效的Java项目25:首选列表而不是数组.
This prints false
. Ugh. See Effective Java Item 25: Prefer lists to arrays for more.
相反,您应该在 Arrays
类可对数组执行此类操作.例如,这将打印true
:
System.out.println(Arrays.equals(new int[]{}, new int[]{}));
So try Arrays.equals()
or JUnit's Assert.assertArrayEquals()
instead of Assert.assertEquals()
:
junit.framework.Assert.assertArrayEquals(
hello.getBytes(),
BaseEncoding.base64().decode(BaseEncoding.base64().encode(hello.getBytes())
)
);
这应该符合预期.
这篇关于无法使Guava base64编码/解码有效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!