本文介绍了如何在Java中将字节数组转换为Base64?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
好的,我知道怎么用C#来做。
Okay, I know how to do it in C#.
这很简单:
Convert.ToBase64String(byte[])
and Convert.FromBase64String(string) to get byte[] back.
我如何用Java做到这一点?
How can I do this in Java?
推荐答案
Java 8 +
对字节数组进行编码或解码:
Java 8+
Encode or decode byte arrays:
byte[] encoded = Base64.getEncoder().encode("Hello".getBytes());
println(new String(encoded)); // Outputs "SGVsbG8="
byte[] decoded = Base64.getDecoder().decode(encoded);
println(new String(decoded)) // Outputs "Hello"
或者如果你只想要字符串:
Or if you just want the strings:
String encoded = Base64.getEncoder().encodeToString("Hello".getBytes());
println(encoded); // Outputs "SGVsbG8="
String decoded = new String(Base64.getDecoder().decode(encoded.getBytes()));
println(decoded) // Outputs "Hello"
有关详细信息,请参阅。
For more info, see Base64.
Base64未捆绑Java版本少于8.我建议使用。
Base64 is not bundled with Java versions less than 8. I recommend using Apache Commons Codec.
对于直接字节数组:
Base64 codec = new Base64();
byte[] encoded = codec.encode("Hello".getBytes());
println(new String(encoded)); // Outputs "SGVsbG8="
byte[] decoded = codec.decode(encoded);
println(new String(decoded)) // Outputs "Hello"
或者如果你只想要字符串:
Or if you just want the strings:
Base64 codec = new Base64();
String encoded = codec.encodeBase64String("Hello".getBytes());
println(encoded); // Outputs "SGVsbG8="
String decoded = new String(codec.decodeBase64(encoded));
println(decoded) // Outputs "Hello"
Android(Java
如果您在Java 8之前使用Android SDK,那么您最好的选择是使用捆绑的 android.util.Base64
。
对于直接字节数组:
byte[] encoded = Base64.encode("Hello".getBytes());
println(new String(encoded)) // Outputs "SGVsbG8="
byte [] decoded = Base64.decode(encoded);
println(new String(decoded)) // Outputs "Hello"
或者如果你只想要字符串:
Or if you just want the strings:
String encoded = Base64.encodeToString("Hello".getBytes());
println(encoded); // Outputs "SGVsbG8="
String decoded = new String(Base64.decode(encoded));
println(decoded) // Outputs "Hello"
这篇关于如何在Java中将字节数组转换为Base64?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!