第一種方式:
通過反射使用java 中不對外公開的類:
![](https://img.laitimes.com/img/_0nNw4CM6IyYiwiM6ICdiwiIn5GcuIXY0N3Xu92Yp9CXzV2Zh1WavwVbvNmLllXZ0lmL3gjN5gzN3gjMxcHavw1LcpDc0RHaiojIsJye.png)
/***
* encode by base64
*/
public static string encodebase64(byte[]input) throws exception{
class clazz=class.forname("com.sun.org.apache.xerces.internal.impl.dv.util.base64");
method mainmethod= clazz.getmethod("encode", byte[].class);
mainmethod.setaccessible(true);
object retobj=mainmethod.invoke(null, new object[]{input});
return (string)retobj;
}
/***
* decode by base64
public static byte[] decodebase64(string input) throws exception{
method mainmethod= clazz.getmethod("decode", string.class);
object retobj=mainmethod.invoke(null, input);
return (byte[])retobj;
第二種方式:
使用commons-codec.jar
![](https://img.laitimes.com/img/_0nNw4CM6IyYiwiM6ICdiwiIn5GcuIXY0N3Xu92Yp9CXzV2Zh1WavwVbvNmLllXZ0lmL3gjN5gzN3gjMxcHavw1LcpDc0RHaiojIsJye.png)
/**
* @param bytes
* @return
public static byte[] decode(final byte[] bytes) {
return base64.decodebase64(bytes);
/**
* 二進制資料編碼為base64字元串
*
* @throws exception
public static string encode(final byte[] bytes) {
return new string(base64.encodebase64(bytes));
第三種方式:
![](https://img.laitimes.com/img/_0nNw4CM6IyYiwiM6ICdiwiIn5GcuIXY0N3Xu92Yp9CXzV2Zh1WavwVbvNmLllXZ0lmL3gjN5gzN3gjMxcHavw1LcpDc0RHaiojIsJye.png)
/**
* 編碼
* @param bstr
* @return string
*/
public static string encode(byte[] bstr){
return new sun.misc.base64encoder().encode(bstr);
}
/**
* 解碼
* @param str
public static byte[] decode(string str){
byte[] bt = null;
try {
sun.misc.base64decoder decoder = new sun.misc.base64decoder();
bt = decoder.decodebuffer( str );
} catch (ioexception e) {
e.printstacktrace();
return bt;