无法使 Guava base64 encode/decode 工作
Unable to make Guava base64 encode/decode work
似乎某处出现了一个非常愚蠢的错误,因为以下 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())
)
));
你支票看的是地址,不知道为什么。如果您查看 byte[] 中的值,您会发现它们匹配。
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]
数组(令人困惑)不会覆盖 Object.equals()
(同样它们不会覆盖 .toString()
,这就是为什么在打印数组时会看到那些 ),这意味着在两个等价数组上调用 .equals()
不会给你预期的结果:
System.out.println(new int[]{}.equals(new int[]{}));
这会打印 false
。啊。请参阅 有效 Java 项目 25:比数组更喜欢列表 了解更多信息。
相反,您应该使用 Arrays
class 中的静态辅助函数来对数组执行此类操作。例如,这会打印 true
:
System.out.println(Arrays.equals(new int[]{}, new int[]{}));
所以尝试 Arrays.equals()
或 JUnit 的 Assert.assertArrayEquals()
而不是 Assert.assertEquals()
:
junit.framework.Assert.assertArrayEquals(
hello.getBytes(),
BaseEncoding.base64().decode(BaseEncoding.base64().encode(hello.getBytes())
)
);
这应该符合预期。
似乎某处出现了一个非常愚蠢的错误,因为以下 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())
)
));
你支票看的是地址,不知道为什么。如果您查看 byte[] 中的值,您会发现它们匹配。
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]
数组(令人困惑)不会覆盖 Object.equals()
(同样它们不会覆盖 .toString()
,这就是为什么在打印数组时会看到那些 .equals()
不会给你预期的结果:
System.out.println(new int[]{}.equals(new int[]{}));
这会打印 false
。啊。请参阅 有效 Java 项目 25:比数组更喜欢列表 了解更多信息。
相反,您应该使用 Arrays
class 中的静态辅助函数来对数组执行此类操作。例如,这会打印 true
:
System.out.println(Arrays.equals(new int[]{}, new int[]{}));
所以尝试 Arrays.equals()
或 JUnit 的 Assert.assertArrayEquals()
而不是 Assert.assertEquals()
:
junit.framework.Assert.assertArrayEquals(
hello.getBytes(),
BaseEncoding.base64().decode(BaseEncoding.base64().encode(hello.getBytes())
)
);
这应该符合预期。