user2250246 user2250246 - 2 months ago 17
Java Question

Unable to make Guava base64 encode/decode work

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?

Answer

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.

Comments