![](/img/trans.png)
[英]Encoding a PDF to Base64 in Java, decoding in PL/SQL: doesn't work
[英]Java Base64 Decoding/Encoding rountrip doesn't come up with same result
import org.junit.Test;
import java.util.Base64;
import org.junit.Assert.*;
import java.util.Random;
...
@Test
public void testEncoding(){
byte[] data = new byte[32];
new Random().nextBytes(data);
String base64 = Base64.getEncoder().encodeToString(data);
assertEquals(data, Base64.getDecoder().decode(base64));
}
@Test
public void testDecoding(){
String base64 = "ABCDEFGHIJKLRMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/A==";
byte[] data = Base64.getDecoder().decode(base64);
assertEquals(base64, Base64.getEncoder().encodeToString(data));
}
testEncoding测试失败,并出现AssertionError:预期:[B @ 6bf2d08e实际:[B @ 5eb5c224而且我不知道为什么。
缺陷在于代码中没有断言。
assertEquals将比较字节数组在内存中的地址assertArrayEquals将比较字节数组的内容
尝试这个。 您应该编码一个普通的String,然后解码一个普通的String,而不是字节数组:
@Test
public void verify() throws Exception {
String normalString = "ABCDEFGHIJKLRMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/A==";
byte[] asBytes = normalString.getBytes();
String encoded = Base64.getEncoder().encodeToString(asBytes);
byte[] decodedBytes = Base64.getDecoder().decode(encoded);
String decoded = new String(decodedBytes);
assertEquals(normalString , decoded);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.