问题
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())
)
);
I even tried hello.getBytes("ISO-8859-1")
What am I missing?
回答1:
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[]{}));
This prints false
. Ugh. See Effective Java Item 25: Prefer lists to arrays for more.
Instead you should use the static helper functions in the Arrays class to do these sort of operations on arrays. For example this prints 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())
)
);
This should behave as expected.
回答2:
If you instead check if the String matches then it does match.
junit.framework.Assert.assertEquals(
hello,
new String(
BaseEncoding.base64().decode(
BaseEncoding.base64().encode(hello.getBytes())
)
));
What your check is looking at is the address, I do not know why. If you look at the values in the byte[]'s you see they match.
System.out.println("hello.getBytes = " + Arrays.toString(hello.getBytes()));
System.out.println("decoded = " + Arrays.toString(BaseEncoding.base64().decode(
BaseEncoding.base64().encode(hello.getBytes())
)
));
which outputs:
hello.getBytes = [104, 101, 108, 108, 111]
decoded = [104, 101, 108, 108, 111]
来源:https://stackoverflow.com/questions/36990210/unable-to-make-guava-base64-encode-decode-work