BASE64 编码是一种常用的字符编码,在很多地方都会用到。JDK 中提供了非常方便的 BASE64Encoder 和 BASE64Decoder,用它们可以非常方便的完成基于 BASE64 的编码和解码。下面是本人编的两个小的函数,分别用于 BASE64 的编码和解码:
view sourceprint
01
import sun.misc.BASE64Encoder;
02
import sun.misc.BASE64Decoder;
03
04
// 将 s 进行 BASE64 编码
05
publicstaticString getBASE64(String s) {
06
if (s == null) returnnull;
07
return (new sun.misc.BASE64Encoder()).encode(s.getBytes());
08
}
09
10
// 将 BASE64 编码的字符串 s 进行解码
publicstaticString getFromBASE64(String s) {
12
if (s == null) returnnull;
13
BASE64Decoder decoder = new BASE64Decoder();
14
try {
15
byte[] b = decoder.decodeBuffer(s);
16
returnnewString(b);
17
} catch (Exception e) {
18
returnnull;
19
}
20
}
作者:liweigov