Java Encode encodeForString(String str)

Here you can find the source of encodeForString(String str)

Description

encode For String

License

Apache License

Declaration

public static String encodeForString(String str) 

Method Source Code


//package com.java2s;
//License from project: Apache License 

import java.io.UnsupportedEncodingException;

public class Main {
    private final static char[] ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
            .toCharArray();//from w  ww.j  a v  a  2s  .  co m

    public static String encodeForString(String str) {
        try {
            return encode(str.getBytes("UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * Translates the specified byte array into Base64 string.
     *
     * @param buf the byte array (not null)
     * @return the translated Base64 string (not null)
     */
    public static String encode(byte[] buf) {
        int size = buf.length;
        char[] ar = new char[((size + 2) / 3) * 4];
        int a = 0;
        int i = 0;
        while (i < size) {
            byte b0 = buf[i++];
            byte b1 = (i < size) ? buf[i++] : 0;
            byte b2 = (i < size) ? buf[i++] : 0;

            int mask = 0x3F;
            ar[a++] = ALPHABET[(b0 >> 2) & mask];
            ar[a++] = ALPHABET[((b0 << 4) | ((b1 & 0xFF) >> 4)) & mask];
            ar[a++] = ALPHABET[((b1 << 2) | ((b2 & 0xFF) >> 6)) & mask];
            ar[a++] = ALPHABET[b2 & mask];
        }
        switch (size % 3) {
        case 1:
            ar[--a] = '=';
        case 2:
            ar[--a] = '=';
        }
        return new String(ar);
    }
}

Related

  1. encodedInputStreamReader(InputStream stream, String encoding)
  2. encodedStringToProperties(String theEncodedPropertyString)
  3. encodeEmail(String s)
  4. encodeFile(String filePath)
  5. encodeForFilter(final String filterString)
  6. encodeGoomojiSubject(String subject)
  7. encodeHeaderValue(String headerName, String headerValue)
  8. encodeHTML(String input, boolean reduceToASCII, boolean useHTMLTags)
  9. encodeHttpHeaderValueAsUTF8(String text)