什么GBK,UTF-8都是浮云,乱码得这样。[Base64加密解密]

本文介绍如何在Java中使用Base64编码和解码字符串,包括编码和解码的方法实现及示例代码,展示了如何将字符串转换为Base64格式并还原。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 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 我爱你




转载于:https://www.cnblogs.com/shudaizi/archive/2012/01/04/2311481.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值