无法让 Base64.decodeBase64 工作(Commons 编解码器)
String encode = Base64.encodeBase64String("Hello".getBytes());
System.out.println(encode);
byte[] decode = Base64.decodeBase64(encode);
System.out.println(decode.toString());
我不知道这里出了什么问题。我已经尝试了所有可能的组合。设置字符集,toString,无toString。编码工作完美。我可以将该数字放入网络解码器中并每次都获得正确的值。只是无法让它发挥作用。
输出:
run:
SGVsbG8= (encode)
[B@1fb8ee3 (decode)
如果我使用 for 循环并手动将字符添加到字符串中,我可以使其工作。但我认为 toString 为我做到了这一点?
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. 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. But I thought toString did that for me?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
眼前的问题是如何将字节数组转换为字符串。
请尝试这样做:
但是,使用
String.getBytes()
或new String(byte[])
的重载通常是一个坏主意其中不指定字符编码。它们使用平台默认编码,这立即意味着您的代码不可移植 - 或者至少您的数据不可移植。我建议您使用常见的编码,例如UTF-8。The immediate problem is how you're converting the byte array to a string.
Try this instead:
However, it's generally a bad idea to use the overloads of
String.getBytes()
ornew String(byte[])
which don't specify a character encoding. 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.数组上的
toString()
不会执行您期望的操作...它只是Object
的默认toString()
实现,它根据对象的哈希码返回一个字符串。尝试new String(decode)
。toString()
on an array doesn't do what you're expecting... it's just the defaulttoString()
implementation fromObject
, which returns a string based on the hashcode of the object. Trynew String(decode)
.