Java String Encode encode(String s, String enc)

Here you can find the source of encode(String s, String enc)

Description

Encode a given string.

License

Open Source License

Parameter

Parameter Description
s String to encode.
enc Encode.

Exception

Parameter Description
IllegalArgumentException If string is empty or null.

Return

Encoded string.

Declaration

public static String encode(String s, String enc) 

Method Source Code


//package com.java2s;
import java.io.ByteArrayInputStream;
import java.io.UnsupportedEncodingException;

public class Main {
    /**/* w  w  w  .j  ava2 s.  c o  m*/
    * <p>
    * Encode a given string. If encode type is not informed, UTF-8 is
    * considered.
    * </p>
    * @param s String to encode.
    * @param enc Encode.
    * @return Encoded string.
    * @throws IllegalArgumentException If string is empty or null.
    */
    public static String encode(String s, String enc) {
        if (s == null) {
            throw new IllegalArgumentException("String must not be null");
        }
        if (enc == null) {
            enc = "UTF-8";
        }
        //
        ByteArrayInputStream bIn;
        //
        try {
            bIn = new ByteArrayInputStream(s.getBytes(enc));
        } catch (UnsupportedEncodingException e) {
            bIn = new ByteArrayInputStream(s.getBytes());
        }
        //
        int c = bIn.read();
        StringBuffer ret = new StringBuffer();
        //
        while (c >= 0) {
            if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '.' || c == '-'
                    || c == '*' || c == '_') {
                ret.append((char) c);
            } else if (c == ' ') {
                ret.append("%20");
            } else {
                if (c < 128) {
                    ret.append(getHexChar(c));
                } else if (c < 224) {
                    ret.append(getHexChar(c));
                    ret.append(getHexChar(bIn.read()));
                } else if (c < 240) {
                    ret.append(getHexChar(c));
                    ret.append(getHexChar(bIn.read()));
                    ret.append(getHexChar(bIn.read()));
                }
            }
            //
            c = bIn.read();
        }
        //
        return ret.toString();
    }

    /**
     * <p>
     * Get a hex value of a char.
     * </p>
     * @param c Char.
     */
    private static String getHexChar(int c) {
        return (c < 16 ? "%0" : "%") + Integer.toHexString(c).toUpperCase();
    }
}

Related

  1. encode(String encoding, String text)
  2. encode(String name)
  3. encode(String s)
  4. encode(String s)
  5. encode(String s)
  6. encode(String s, String encoding)
  7. encode(String source, String charsetFrom, String charsetTo)
  8. encode(String src)
  9. encode(String src, String charset)