Decode Base64 data in Java
I have an image that is Base64 encoded. What is the best way to decode that in Java? Hopefully using only the libraries included with Sun Java 6.
As of v6, Java SE ships with JAXB. javax.xml.bind.DatatypeConverter
has static methods that make this easy. See parseBase64Binary()
and printBase64Binary()
.
As of Java 8 , there is an officially supported API for Base64 encoding and decoding. In time this will probably become the default choice.
The API includes the class java.util.Base64
and its nested classes. It supports three different flavors: basic, URL safe, and MIME.
Sample code using the "basic" encoding:
import java.util.Base64;
byte[] bytes = "Hello, World!".getBytes("UTF-8");
String encoded = Base64.getEncoder().encodeToString(bytes);
byte[] decoded = Base64.getDecoder().decode(encoded);
The documentation for java.util.Base64
includes several more methods for configuring encoders and decoders, and for using different classes as inputs and outputs (byte arrays, strings, ByteBuffers, java.io streams).
Here is a working example using Apache Commons codec:
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.StringUtils;
public String decode(String s) {
return StringUtils.newStringUtf8(Base64.decodeBase64(s));
}
public String encode(String s) {
return Base64.encodeBase64String(StringUtils.getBytesUtf8(s));
}
Maven / sbt repo: commons-codec, commons-codec, 1.8.
链接地址: http://www.djcxy.com/p/22136.html上一篇: 将Base64背景图像数据嵌入到CSS中作为好还是不好的做法?
下一篇: 用Java解码Base64数据