Java后台判断中文是否乱码,如果乱码进行解码处理解决办法

/**

* 判断是否为乱码

* @param cqrunnerxjzh date:2017.11.08

*/

private static boolean isChinese(char c) {

Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);

if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS

|| ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS

|| ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A

|| ub == Character.UnicodeBlock.GENERAL_PUNCTUATION

|| ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION

|| ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS) {

return true;

}

return false;

}

/**

* 判断是否为乱码

* @param cqrunnerxjzh date:2017.11.08

*/

public static boolean isMessyCode(String strName) {

Pattern p = Pattern.compile("\\s*|\t*|\r*|\n*");

Matcher m = p.matcher(strName);

String after = m.replaceAll("");

String temp = after.replaceAll("\\p{P}", "");

char[] ch = temp.trim().toCharArray();

float chLength = 0 ;

float count = 0;

for (int i = 0; i < ch.length; i++) {

char c = ch[i];

if (!Character.isLetterOrDigit(c)) {

if (!isChinese(c)) {

count = count + 1;

}

chLength++;

}

}

float result = count / chLength ;

if (result > 0.4) {

return true;

} else {

return false;

}

}

/**

* 中文乱码处理

* @param cqrunnerxjzh date:2017.11.08

*/

public static String toChinese(String str){

if(isMessyCode(str)){

try {

return new String(str.getBytes("ISO8859-1"), "UTF-8");

} catch (Exception e) {

}

}

return str;

}

你可能感兴趣的:(Java后台判断中文是否乱码,如果乱码进行解码处理解决办法)