---
title: "Java 识别字符编码"
author: "darkma"
date: "2011-05-26T10:25:02Z"
tags: ["Java"]
categories: ["编程语言"]
slug: "java"
draft: false
lastmod: "2011-08-04T14:37:06Z"
id: 1059248
url: "https://darkmasky.iteye.com/blog/1059248"
---

public class EncodingUtils {

 

// 识别字符串编码

public static String getEncoding(String str) {

if (str == null || str.trim().length() &lt; 1)

return "";

// 常用字符编码数组

String\[] encodes = new String\[] { "GBK", "ISO-8859-1", "GB2312",

"GB18030", "UTF-8" };

for (String encode : encodes) {

try {

// 匹配字符编码

if (str.equals(new String(str.getBytes(), encode))) {

// 返回编码名称

return encode;

} else {

continue;

}

} catch (Exception er) {

}

}

return "";

}

}