孙肖宁

java中对字符串进行Base64编码/解码的问题
java本身转码解码编码 public static String getBASE64(String str) ...
扫描右侧二维码阅读全文
15
2019/03

java中对字符串进行Base64编码/解码的问题

java本身转码解码

  • 编码

      public static String getBASE64(String str) {
           if (str == null) return null;
           return (new sun.misc.BASE64Encoder()).encode( str.getBytes() );
      }
  • 解码

    public static String getFromBASE64(String str) {
           if (str == null) return null;
           BASE64Decoder decoder = new BASE64Decoder();
           try {
               byte[] b = decoder.decodeBuffer(s);
               return new String(b);
           } catch (Exception e) {
               return null;
           }
       }

    利用apache的包

  • 编码

         public static String encode(byte[] binaryData) {
           try {
               return new String(Base64.encodeBase64(binaryData), "UTF-8");
           } catch (UnsupportedEncodingException e) {
               return null;
           }
       }
  • 解码
  public static byte[] decode(String base64String) {
        try {
            return Base64.decodeBase64(base64String.getBytes("UTF-8"));
        } catch (UnsupportedEncodingException e) {
            return null;
        }
    } 
Last modification:March 15th, 2019 at 11:37 am
If you think my article is useful to you, please feel free to appreciate

Leave a Comment