在Java中如何进行BASE64编码和解码

时间:2023-12-17 10:29:14
  • 在Java中如何进行BASE64编码和解码

//在Java中如何进行BASE64编码和解码
package me.xzh.study.sun.misc.BASE64; import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder; public class BASE64_Test
{
// 将 s 进行 BASE64 编码
public static String getBASE64(String s)
{
if (s == null) return null;
return (new sun.misc.BASE64Encoder()).encode( s.getBytes() );
}
// 将 BASE64 编码的字符串 s 进行解码
public static String getFromBASE64(String s)
{
if (s == null) return null;
BASE64Decoder decoder = new BASE64Decoder();
try {
byte[] b = decoder.decodeBuffer(s);
return new String(b);
} catch (Exception e)
{
return null;
}
}
public static void main(String[] args) throws Exception
{
System.out.println("BASE64编码后:" + BASE64_Test.getBASE64("ab"));
System.out.println("BASE64解码后:" + BASE64_Test.getFromBASE64("YWI="));
}
}

运行结果如下:

在Java中如何进行BASE64编码和解码