简体   繁体   English

无法使Base64.decodeBase64工作(通用编解码器)

[英]Can't get Base64.decodeBase64 to work (Commons codec)

String encode = Base64.encodeBase64String("Hello".getBytes());
System.out.println(encode);
byte[] decode = Base64.decodeBase64(encode);
System.out.println(decode.toString());

I can't tell whats wrong here. 我无法在这里说出什么问题。 I've tried every possible combination there is. 我尝试了所有可能的组合。 Set the charset, toString, no toString. 设置字符集toString,不设置toString。 The encode works perfectly. 编码工作完美。 I can throw that number into a web decoder and get the right value every time. 我可以将该数字放入网络解码器中,并每次获取正确的值。 Just can't get this to work. 只是无法使它正常工作。

Output: 输出:

 run:
SGVsbG8= (encode)

[B@1fb8ee3  (decode)

I can make it work if I use a for loop and manually add the characters to a string. 如果使用for循环并手动将字符添加到字符串中,则可以使其工作。 But I thought toString did that for me? 但是我以为toString对我有用吗?

The immediate problem is how you're converting the byte array to a string. 眼前的问题是如何将字节数组转换为字符串。

Try this instead: 试试这个:

System.out.println(new String(decode));

However , it's generally a bad idea to use the overloads of String.getBytes() or new String(byte[]) which don't specify a character encoding. 但是 ,使用String.getBytes()或不指定字符编码的new String(byte[])的重载通常是一个坏主意。 They use the platform default encoding, which immediately means your code isn't portable - or at least, your data isn't. 他们使用平台默认编码,这立即意味着您的代码不可移植-至少,您的数据不可移植。 I suggest you use a common encoding such as UTF-8. 我建议您使用通用编码,例如UTF-8。

toString() on an array doesn't do what you're expecting... it's just the default toString() implementation from Object , which returns a string based on the hashcode of the object. 数组上的toString()并没有达到您的期望……这只是Object的默认toString()实现,该实现基于对象的哈希码返回一个字符串。 Try new String(decode) . 尝试new String(decode)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM