1 private static BASE64Encoder encoder = new BASE64Encoder();
2 private static BASE64Decoder decoder = new BASE64Decoder();
3 /**
4 * BASE64 编码
5 *
6 * @param s
7 * @return
8 */
9 public static String encodeBufferBase64(byte[] buff)
10 {
11 return buff == null?null:encoder.encodeBuffer(buff).trim();
12 }
13
14
15 /**
16 * BASE64解码
17 *
18 * @param s
19 * @return
20 */
21 public static byte[] decodeBufferBase64(String s)
22 {
23 try
24 {
25 return s == null ? null : decoder.decodeBuffer(s);
26 }
27 catch (IOException e)
28 {
29 e.printStackTrace();
30 }
31 return null;
32 }
33
34
35 /**
36 * base64编码
37 *
38 * @param bytes
39 * 字符数组
40 * @return
41 * @throws IOException
42 */
43 public static String encodeBytes(byte[] bytes) throws IOException
44 {
45 return new BASE64Encoder().encode(bytes).replace("\n", "").replace("\r", "");
46 }
47
48 /**
49 * base64解码
50 *
51 * @param bytes
52 * 字符数组
53 * @return
54 * @throws IOException
55 */
56 public static String decodeBytes(byte[] bytes) throws IOException
57 {
58 return new String(new BASE64Decoder().decodeBuffer(new String(bytes)));
59 }
测试代码
public static void main(String[] args) throws Exception
{
String str1="我爱你";
String s=encodeBufferBase64(str1.getBytes());
System.out.println(s);
String strs=new String(decodeBufferBase64(s));
System.out.println(strs);
}
控制台打印
1 ztKwrsTj
2 我爱你