我想知道哪个库可用于base64编码/解码?我需要此功能足够稳定以供生产使用。
我想知道哪个库可用于base64编码/解码?我需要此功能足够稳定以供生产使用。
请使用Java 8的解决方案。请注意,DatatypeConverter仍然可以使用,但现在它在java.xml.bind
模块中,需要将其包含在内。
module org.example.foo {
requires java.xml.bind;
}
Java 8现在提供java.util.Base64
用于编码和解码base64。
编码
byte[] message = "hello world".getBytes(StandardCharsets.UTF_8);
String encoded = Base64.getEncoder().encodeToString(message);
System.out.println(encoded);
// => aGVsbG8gd29ybGQ=
解码
byte[] decoded = Base64.getDecoder().decode("aGVsbG8gd29ybGQ=");
System.out.println(new String(decoded, StandardCharsets.UTF_8));
// => hello world
自从Java 6版本起,较为不为人知的类javax.xml.bind.DatatypeConverter
可以被使用。这是JRE的一部分,无需额外的库。
编码
byte[] message = "hello world".getBytes("UTF-8");
String encoded = DatatypeConverter.printBase64Binary(message);
System.out.println(encoded);
// => aGVsbG8gd29ybGQ=
解码
byte[] decoded = DatatypeConverter.parseBase64Binary("aGVsbG8gd29ybGQ=");
System.out.println(new String(decoded, "UTF-8"));
// => hello world
在 Apache Commons 中,commons-codec-1.7.jar 包含一个 Base64 类,可以用于编码。
通过 Maven:
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>20041127.091804</version>
</dependency>
android.util.Base64
类来实现此目的。Base64
在 API 级别 8 中被添加,这基本上意味着它在存在的所有设备上都得到支持。 - nitzanjBase64
类:android.util.Base64
(自API 8以来)和java.util.Base64
(自API 26以来)。导入时要注意包名。 - Andrew T.Guava还有Base64(以及其他编码和非常有用的内容)