base64.java

来自「短信系统SMS:支持普通短信、长短信和wap push短信的发送。」· Java 代码 · 共 90 行

JAVA
90
字号
package com.ekun.common.util;

/**
 * <p>Title: </p>
 *
 * <p>Description: </p>
 *
 * <p>Copyright: Copyright (c) 2006</p>
 *
 * <p>Company: </p>
 *
 * @author ekun
 * @version 1.0
 */
import java.io.InputStream;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class Base64
{
    /**
     * 编码方法, 把一个字节数组编码为BASE64编码的字符串
     * @param arrB 需要编码的字节数组
     * @return BASE64编码的字符串
     */
    public static String encode(byte[] arrB){
        if(arrB == null){
            return null;
        }
        return new BASE64Encoder().encode(arrB);
    }

    /**
     * 解码方法, 把一个BASE64编码的字符串解码为编码前的字节数组
     * @param in 需要解码的BASE64编码的字符串
     * @return 解码后的字节数组, 若解码失败(该字符串不是BASE64编码)则返回null
     */
    public static byte[] decode(String in){
        byte[] arrB = null;
        try{
            arrB = new BASE64Decoder().decodeBuffer(in);
        } catch(Exception ex){
            arrB = null;
        }
        return arrB;
    }

    /**
     * 单元测试方法, 打印一个字符串在内存中的二进制值
     * @param in 需要打印的字符串
     */
    public static void printByte(String in){
        byte[] arrB = in.getBytes();
        for(int i = 0; i < arrB.length; i++){
            System.out.print(Integer.toHexString(arrB[i]) + " ");
        }
        System.out.println();
    }

    /**
     * 编码方法, 把InputStream流中的数据内容编码为BASE64编码的字符串
     * @param in 需要编码的字节数组
     * @return BASE64编码的字符串
     */
    public static String encode(InputStream in){
        if(in == null){
            return null;
        }
        byte[] read = new byte[64];
        StringBuffer result = new StringBuffer("");
        try{
            int bytesRead = -1;
            while((bytesRead = in.read(read)) != -1){
                byte[] src = read;
                if(bytesRead != 64){
                    src = new byte[bytesRead];
                    for(int j = 0; j < bytesRead; j++){
                        src[j] = read[j];
                    }
                }
                result.append(Base64.encode(src));
            }
        } catch(Exception e){
            e.printStackTrace();
            return null;
        }
        return result.toString();
    }
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?