Android UTF8 Encode utf8Encode(String str, String defultReturn)

Here you can find the source of utf8Encode(String str, String defultReturn)

Description

encoded in utf-8, if exception, return defultReturn

Parameter

Parameter Description
str a parameter
defultReturn a parameter

Declaration

public static String utf8Encode(String str, String defultReturn) 

Method Source Code

//package com.java2s;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

public class Main {

    public static String utf8Encode(String str) {
        if (!isEmpty(str) && str.getBytes().length != str.length()) {
            try {
                return URLEncoder.encode(str, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                throw new RuntimeException(
                        "UnsupportedEncodingException occurred. ", e);
            }// w  w  w  .  j  a v  a2 s. co m
        }
        return str;
    }

    /**
     * encoded in utf-8, if exception, return defultReturn
     * 
     * @param str
     * @param defultReturn
     * @return
     */
    public static String utf8Encode(String str, String defultReturn) {
        if (!isEmpty(str) && str.getBytes().length != str.length()) {
            try {
                return URLEncoder.encode(str, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                return defultReturn;
            }
        }
        return str;
    }

    /**
     * is null or its length is 0
     * 
     * <pre>
     * isEmpty(null) = true;
     * isEmpty(&quot;&quot;) = true;
     * isEmpty(&quot;  &quot;) = false;
     * </pre>
     * 
     * @param str
     * @return if string is null or its size is 0, return true, else return false.
     */
    public static boolean isEmpty(String str) {
        return (str == null || str.length() == 0);
    }
}

Related

  1. utf8Encode(String str)
  2. toUtf8(String str)
  3. bytesUtf8(int c)
  4. bytes2StringUTF8(byte[] buf)
  5. bytes2StringUTF8(byte[] buf, int bufOffset, int bufLength, boolean bigEndian)