哪个Java库提供base64编码/解码?
我想知道哪个库用于base64编码/解码?我需要这个功能足够稳定以供生产使用。
I am wondering which library to use for base64 encoding/decoding? I need this functionality be stable enough for production use.
Java 9
使用Java 8解决方案。注意仍然可以使用DatatypeConverter,但它现在位于 java.xml.bind
模块中,需要包含该模块。
Java 9
Use the Java 8 solution. Note DatatypeConverter can still be used, but it is now within the java.xml.bind
module which will need to be included.
module org.example.foo {
requires java.xml.bind;
}
Java 8
Java 8现在提供 java。 util.Base64
用于编码和解码base64。
Java 8
Java 8 now provides java.util.Base64
for encoding and decoding 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和7
从Java 6开始,鲜为人知的类 javax.xml.bind.DatatypeConverter 。这是JRE的一部分,不需要额外的库。
Java 6 and 7
Since Java 6 the lesser known class javax.xml.bind.DatatypeConverter
can be used. This is part of the JRE, no extra libraries required.
编码
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