服务热线:13616026886

技术文档 欢迎使用技术文档,我们为你提供从新手到专业开发者的所有资源,你也可以通过它日益精进

位置:首页 > 技术文档 > JAVA > 新手入门 > 基础入门 > 查看文档

在 java 中如何进行 base64 编码和解码


  base64 编码是一种常用的字符编码,在很多地方都会用到。jdk 中提供了非常方便的 base64encoder 和 base64decoder,用它们可以非常方便的完成基于 base64 的编码和解码。下面是本人编的两个小的函数,分别用于 base64 的编码和解码:
  
  // 将 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;
  }
  }

扫描关注微信公众号