问题描述
好的,我知道如何在 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"
有关详细信息,请参阅Base64.
For more info, see Base64.
Base64 不与低于 8 的 Java 版本捆绑在一起.我建议使用 Apache Commons编解码器.
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"
春天
如果您已经在 Spring 项目中工作,您可能会发现他们的 org.springframework.util.Base64Utils
类更符合人体工程学:
Spring
If you're working in a Spring project already, you may find their org.springframework.util.Base64Utils
class more ergonomic:
对于直接字节数组:
byte[] encoded = Base64Utils.encode("Hello".getBytes());
println(new String(encoded)) // Outputs "SGVsbG8="
byte[] decoded = Base64Utils.decode(encoded);
println(new String(decoded)) // Outputs "Hello"
或者如果你只想要字符串:
Or if you just want the strings:
String encoded = Base64Utils.encodeToString("Hello".getBytes());
println(encoded); // Outputs "SGVsbG8="
String decoded = Base64Utils.decodeFromString(encoded);
println(new String(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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!