程序代码:
package import *;
import *;
public class CodingConvert {
public CodingConvert() {}
public static String sqlConvert(String sql) throws
UnsupportedEncodingException {
return convertEncoding(sql, "GBK", "ISO-8859-1");
}
/**
* 将ISO-8859-1字符集转化为gb2312字符集
* @param srcText 源字符串
* @return destText 目标字符串
* @throws UnsupportedEncodingException 不支持字符集异常
*/
public static String isoToGBK(String srcText) throws
UnsupportedEncodingException {
return convertEncoding(srcText, "ISO-8859-1", "GBK");
}
/**
* 将gb2312字符集转化为ISO-8859-1字符集
* @param srcText 源字符串
* @return destText 目标字符串
* @throws UnsupportedEncodingException 不支持字符集异常
*/
public static String GBKToIso(String srcText) throws
UnsupportedEncodingException {
try {
return convertEncoding(srcText, "GBK", "ISO-8859-1");
}
catch (UnsupportedEncodingException e) {
e.printStackTrace();
return srcText;
}
}
/**
* 代码字符集转换
* @param str 原始字符串
* @param sourEncoding 源代码字符集
* @param destEncoding 目标代码字符集
* @return result 转换后字符串
* @throws UnsupportedEncodingException 不支持字符集异常
*/
public static String convertEncoding(String str,
String sourEncoding,
String destEncoding) throws
UnsupportedEncodingException {
if (str == null || str.equals(""))
return "";
int convertNum = 0;
char[] inputChars = new char[str.length()];
CharToByteConverter ctbConverter = (CharToByteConverter)
CharToByteConverter.getConverter(sourEncoding);
ctbConverter.setSubstitutionMode(false);
for (int i = 0; i < str.length(); i++) {
if (ctbConverter.canConvert(str.charAt(i))) {
inputChars[convertNum++] = str.charAt(i);
}
else {
if (ctbConverter.canConvert(str.charAt(i))) {
inputChars[convertNum++] = str.charAt(i);
}
else {
return str;
}
}
}
byte[] outputBytes = new byte[inputChars.length * 2];
try {
int count = ctbConverter.convert(inputChars, 0, inputChars.length,
outputBytes, 0, outputBytes.length);
}
catch (Exception e) {
System.out.println("1");
e.printStackTrace();
}
ByteToCharConverter btcConverter = ByteToCharConverter.getConverter(
destEncoding);
char[] outputChars = new char[outputBytes.length];
try {
int count = btcConverter.convert(outputBytes, 0, outputBytes.length,
outputChars, 0, outputChars.length);
}
catch (Exception e) {
System.out.println("2");
e.printStackTrace();
}
String result = new String(outputChars);
return result.trim();
}
}