1. a way
import java.io.UnsupportedEncodingException; import java.util.Base64; // byte[]转base64 String base64Str = Base64.getEncoder().encodeToString(byteArray); // base64转byte[] byte[] byteArray = Base64.getDecoder().decode(base64Str);
Note: Use jdk own Base64.java class implementation, but jdk version must be> = 1.8.
2. Second way
import java.io.UnsupportedEncodingException; import javax.xml.bind.DatatypeConverter; // byte[]转base64 String base64Str = DatatypeConverter.printBase64Binary(byteArray); // base64转byte[] byte[] byteArray = DatatypeConverter.parseBase64Binary(base64Str);
Note: Use jdk own DatatypeConverter.java class implementation, but jdk version must be> = 1.6.
3. Three ways
import java.io.UnsupportedEncodingException; import org.apache.commons.codec.binary.Base64; // byte[]转base64 String base64Str =Base64.encodeBase64String(byteArray).replaceAll("\r\n", ""); // base64转byte[] byte[] byteArray = Base64.decodeBase64(base64Str);
Required jar package: commons-codec.jar
4. Comparison of Efficiency
Fast -> Slow: Second way> a way> Three ways
Thus, if the project using a jdk1.8, the best choice is the second approach; JDK1.6, the best choice is a way.
Written in the last
Which big brother If it is found there is leakage of the carelessness of the article or need to add more content, welcome message! ! !
related suggestion: