java base64编码和解码
2015-06-02 22:37
441 查看
原文:http://hw1287789687.iteye.com/blog/1910853
第一种方式:
通过反射使用java 中不对外公开的类:
/***
* 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{
Class clazz=Class.forName("com.sun.org.apache.xerces.internal.impl.dv.util.Base64");
Method mainMethod= clazz.getMethod("decode", String.class);
mainMethod.setAccessible(true);
Object retObj=mainMethod.invoke(null, input);
return (byte[])retObj;
}
第二种方式:使用commons-codec.jar
/**
* @param bytes
* @return
*/
public static byte[] decode(final byte[] bytes) {
return Base64.decodeBase64(bytes);
}
/**
* 二进制数据编码为BASE64字符串
*
* @param bytes
* @return
* @throws Exception
*/
public static String encode(final byte[] bytes) {
return new String(Base64.encodeBase64(bytes));
}
第三种方式:
/**
* 编码
* @param bstr
* @return String
*/
public static String encode(byte[] bstr){
return new sun.misc.BASE64Encoder().encode(bstr);
}
/**
* 解码
* @param str
* @return string
*/
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;
}
相关文章推荐
- 《奇妙的NULL值,你知道多少?》
- Struts文件上传allowedTypes问题,烦人的“允许上传的文件类型”
- #JAVA操作LDAP
- Java 连接、操控数据库总结(JDBC)
- HDU1850 Being a Good Boy in Spring Festival
- Java系统变量设置方式
- struts2快速入门
- [Android Studio系列(一)] eclipse项目导入Android Studio的2种方法
- 【Struts0002】Difference between # , $ and % signs in Struts2
- ubuntu下 Sublime Text 3配置基本Java环境
- JAVA堆算法,基于数组实现
- 基于java的双向链表实现方法
- Eclipse NDK 配置
- java多线程的实现和比较
- Extjs+Struts学习资料
- java学习之其他对象API
- 【Struts2】If, Else, ElseIf Conditional/Control tag example in Struts 2
- Java中的wait、notify、notifyall方法
- Spring框架之自动装配
- java中compareTo和compare方法之比较