Java通过JavaMail的MimeUtility对字符串进行Base64编码

2018-07-20    来源:open-open

容器云强势上线!快速搭建集群,上万Linux镜像随意使用
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

import javax.mail.internet.MimeUtility;

public class Base64 {
 public static byte[] encode(byte[] b) throws Exception {
  ByteArrayOutputStream baos = null;
  OutputStream b64os = null;
  try {
   baos = new ByteArrayOutputStream();
   b64os = MimeUtility.encode(baos, "base64");
   b64os.write(b);
   b64os.close();
   return baos.toByteArray();
  } catch (Exception e) {
   throw new Exception(e);
  } finally {
   try {
    if (baos != null) {
     baos.close();
     baos = null;
    }
   } catch (Exception e) {
   }
   try {
    if (b64os != null) {
     b64os.close();
     b64os = null;
    }
   } catch (Exception e) {
   }
  }
 }

 public static byte[] decode(byte[] b) throws Exception {
  ByteArrayInputStream bais = null;
  InputStream b64is = null;
  try {
   bais = new ByteArrayInputStream(b);
   b64is = MimeUtility.decode(bais, "base64");
   byte[] tmp = new byte[b.length];
   int n = b64is.read(tmp);
   byte[] res = new byte[n];
   System.arraycopy(tmp, 0, res, 0, n);

   return res;
  } catch (Exception e) {
   throw new Exception(e);
  } finally {
   try {
    if (bais != null) {
     bais.close();
     bais = null;
    }
   } catch (Exception e) {
   }
   try {
    if (b64is != null) {
     b64is.close();
     b64is = null;
    }
   } catch (Exception e) {
   }
  }
 }
}

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点!
本站所提供的图片等素材,版权归原作者所有,如需使用,请与原作者联系。

上一篇:Java 使用 NIO 方式读文件

下一篇:java 实现的Boyer-Moore(BM)算法