Java String Encode encodeString(String strData)

Here you can find the source of encodeString(String strData)

Description

encode String to Base64

License

Open Source License

Parameter

Parameter Description
strData a parameter

Declaration

public static String encodeString(String strData) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.io.IOException;

public class Main {
    private static final char[] base64EncodeChars = new char[] { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',
            'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e',
            'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
            '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/' };

    /**/*from w  ww.j  ava  2s.  c o  m*/
     * encode String to Base64
     * @param strData
     */
    public static String encodeString(String strData) {
        if (strData == null)
            return "";

        try {
            byte[] bytes = strData.getBytes("UTF8");
            return encode(bytes).replace("\n", "");
        } catch (IOException ie) {
            ie.printStackTrace();
        }

        return "";
    }

    public static String encode(byte[] data) {
        StringBuffer sb = new StringBuffer();
        int len = data.length;
        int i = 0;
        int b1, b2, b3;

        while (i < len) {
            b1 = data[i++] & 0xff;
            if (i == len) {
                sb.append(base64EncodeChars[b1 >>> 2]);
                sb.append(base64EncodeChars[(b1 & 0x3) << 4]);
                sb.append("==");
                break;
            }
            b2 = data[i++] & 0xff;
            if (i == len) {
                sb.append(base64EncodeChars[b1 >>> 2]);
                sb.append(base64EncodeChars[((b1 & 0x03) << 4) | ((b2 & 0xf0) >>> 4)]);
                sb.append(base64EncodeChars[(b2 & 0x0f) << 2]);
                sb.append("=");
                break;
            }
            b3 = data[i++] & 0xff;
            sb.append(base64EncodeChars[b1 >>> 2]);
            sb.append(base64EncodeChars[((b1 & 0x03) << 4) | ((b2 & 0xf0) >>> 4)]);
            sb.append(base64EncodeChars[((b2 & 0x0f) << 2) | ((b3 & 0xc0) >>> 6)]);
            sb.append(base64EncodeChars[b3 & 0x3f]);
        }
        return sb.toString();
    }
}

Related

  1. encodeString(String s, boolean useUnicode)
  2. encodeString(String s, Integer size)
  3. encodeString(String s, String charset)
  4. encodeString(String sourceString, String sysCharset, String charset)
  5. encodeString(String str)
  6. encodeString(String text, String charsetName)
  7. encodeString(String value)
  8. encodeStringByUTF8(String str)
  9. encodeText(String str)