更新时间:2023-11-07 17:19:46
使用javax.mail.internet.MimeUtility
Using javax.mail.internet.MimeUtility
import javax.mail.internet.MimeUtility;
import java.io.*;
public class Base64Utils {
private Base64Utils() {}
public static byte[] encode(byte[] b) throws Exception {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
OutputStream b64os = MimeUtility.encode(baos, "base64");
b64os.write(b);
b64os.close();
return baos.toByteArray();
}
public static byte[] decode(byte[] b) throws Exception {
ByteArrayInputStream bais = new ByteArrayInputStream(b);
InputStream b64is = MimeUtility.decode(bais, "base64");
byte[] tmp = new byte[b.length];
int n = b64is.read(tmp);
byte[] res = new byte[n];
System.arraycopy(tmp, 0, res, 0, n);
return res;
}
使用Apache Commons
Using Apache Commons
import org.apache.commons.codec.binary.Base64;
public class Codec {
public static void main(String[] args) {
try {
String clearText = "Hello world";
String encodedText;
// Base64
encodedText = new String(Base64.encodeBase64(clearText.getBytes()));
System.out.println("Encoded: " + encodedText);
System.out.println("Decoded:"
+ new String(Base64.decodeBase64(encodedText.getBytes())));
//
// output :
// Encoded: SGVsbG8gd29ybGQ=
// Decoded:Hello world
//
}
catch (Exception e) {
e.printStackTrace();
}
}
}
使用sun.misc.BASE64Encoder
Using sun.misc.BASE64Encoder
import java.io.IOException;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
// Java Base64 Encoder / Java Base64 Decoder Example
public class Base64Test {
public static void main(String[] args) {
BASE64Decoder decoder = new BASE64Decoder();
BASE64Encoder encoder = new BASE64Encoder();
try {
String encodedBytes = encoder.encodeBuffer("JavaTips.net".getBytes());
System.out.println("encodedBytes " + encodedBytes);
byte[] decodedBytes = decoder.decodeBuffer(encodedBytes);
System.out.println("decodedBytes " + new String(decodedBytes));
} catch (IOException e) {
e.printStackTrace();
}
}
}
参考: http://www.rgagnon.com/javadetails/java-0598.html http://www.javatips.net/blog/2011/08/how-to-encode-and-decode-in-base64-using-java