get Encoding from String - Android java.lang

Android examples for java.lang:String Unicode

Description

get Encoding from String

Demo Code


//package com.java2s;
import java.util.ArrayList;
import java.util.List;

public class Main {
    public static final List<String> SUPPORT_CHARSET = new ArrayList();

    public static String getEncoding(String str, int judgeCharsetLength) {
        String encode = "ISO-8859-1";
        for (String charset : SUPPORT_CHARSET) {
            if (isCharset(str, charset, judgeCharsetLength)) {
                encode = charset;//from  w ww .  j  av a 2  s . c  om
                break;
            }
        }
        return encode;
    }

    public static boolean isCharset(String str, String charset,
            int judgeCharsetLength) {
        try {
            String temp = str.length() > judgeCharsetLength ? str
                    .substring(0, judgeCharsetLength) : str;
            return temp.equals(new String(temp.getBytes(charset), charset));
        } catch (Throwable e) {
        }
        return false;
    }
}

Related Tutorials