有如下三種方式:
方式一:commons-codec.jar
![](https://img.laitimes.com/img/_0nNw4CM6IyYiwiM6ICdiwiIn5GcuIXY0N3Xu92Yp9CXzV2Zh1WavwVbvNmLllXZ0lmL3gjN5gzN3gjMxcHavw1LcpDc0RHaiojIsJye.png)
string base64string = "whuang123";
byte[] result = base64.encodebase64(base64string.getbytes());
方式二:使用sun.misc.base64encoder
![](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;
方式三:使用com.sun.org.apache.xerces.internal.impl.dv.util.base64
![](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;
測試:
![](https://img.laitimes.com/img/_0nNw4CM6IyYiwiM6ICdiwiIn5GcuIXY0N3Xu92Yp9CXzV2Zh1WavwVbvNmLllXZ0lmL3gjN5gzN3gjMxcHavw1LcpDc0RHaiojIsJye.png)
package com.jn.base64;
import junit.framework.assert;
import org.apache.commons.codec.binary.base64;
import com.common.util.systemutil;
public class basetest {
public static void main(string[] args) throws exception {
string base64string = "whuang123";
systemutil.printbytes(result);
byte[] result2 = systemutil.encode(base64string.getbytes()).getbytes();
system.out.println("result2:"+result2);
byte[] result3 = systemutil.encodebase64(base64string.getbytes()).getbytes();
boolean issuccess = systemutil.issame(result, result2);
assert.assertequals(true, issuccess);
systemutil.printbytes(result2);
systemutil.printbytes(result3);
system.out.println(issuccess);
}
運作結果如下: