在Java中,可以使用以下三种方式进行base64编码和解码:
使用Java8的java.util.Base64类(推荐)import java.util.Base64;// 编码String encodedString = Base64.getEncoder().encodeToString("Hello World".getBytes());// 解码byte[] decodedBytes = Base64.getDecoder().decode(encodedString);String decodedString = new String(decodedBytes);
使用Apache Commons Codec库import org.apache.commons.codec.binary.Base64;// 编码String encodedString = Base64.encodeBase64String("Hello World".getBytes());// 解码byte[] decodedBytes = Base64.decodeBase64(encodedString);String decodedString = new String(decodedBytes);
使用Java的sun.misc.BASE64Encoder和sun.misc.BASE64Decoder类(不推荐,因为sun.misc包是不建议使用的内部API)import sun.misc.BASE64Decoder;import sun.misc.BASE64Encoder;// 编码BASE64Encoder encoder = new BASE64Encoder();String encodedString = encoder.encode("Hello World".getBytes());// 解码BASE64Decoder decoder = new BASE64Decoder();byte[] decodedBytes = decoder.decodeBuffer(encodedString);String decodedString = new String(decodedBytes);
注意:在Java9中,sun.misc包被标记为不推荐使用,建议使用Java8的Base64类或Apache Commons Codec库。