我是在WindowsXP下做开发的,应用部署在Linux系统上。
现在有一个自动生成编号的功能需要取汉字拼音的大写首字母,我在windows环境下测试是正常的,可以获得汉字拼音的大写首字母,但是在linux环境下测试确无法正常获取汉字拼音的大写首字母。
我个人感觉是因为系统的默认编码不同引起的,windows的默认编码是GBK,Linux是UTF-8的。
我在java代码中尝试转换编码,但是没有作用,而且java内部应该是unicode编码的,不知道为什么会出现这个问题,难道java的编码转换依赖操作系统?现在这个问题该如何解决?请各位帮帮忙,小弟拜谢。
如果有根据utf-8编码获取汉字拼音大写首字母的代码,也请帮忙贴出来给我参考下,谢谢!
这是那段获得汉字拼音大写首字母的代码,是我在网上找的,应该是根据GBK的编码算出来汉字拼音的大写首字母。import java.io.UnsupportedEncodingException;
import java.util.Hashtable;public class GetFirstLetter { // 国标码和区位码转换常量
private static final int GB_SP_DIFF = 160; // 存放国标一级汉字不同读音的起始区位码
private static final int[] secPosvalueList = { 1601, 1637, 1833, 2078,
2274, 2302, 2433, 2594, 2787, 3106, 3212, 3472, 3635, 3722, 3730,
3858, 4027, 4086, 4390, 4558, 4684, 4925, 5249, 5600 }; // 存放国标一级汉字不同读音的起始区位码对应读音
private static final char[] firstLetter = { 'a', 'b', 'c', 'd', 'e', 'f',
'g', 'h', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't',
'w', 'x', 'y', 'z' }; // 获取一个字符串的拼音码
public static String getFirstLetter(String oriStr) {
String str = oriStr.toLowerCase();
Hashtable ht = System.getProperties();
System.out.println(ht.get("file.encoding"));   
StringBuffer buffer = new StringBuffer();
char ch;
char[] temp;
for (int i = 0; i < str.length(); i++) { // 依次处理str中每个字符
ch = str.charAt(i);
temp = new char[] { ch };
byte[] uniCode = new String(temp).getBytes();
if (uniCode[0] < 128 && uniCode[0] > 0) { // 非汉字
buffer.append(temp);
} else {
buffer.append(convert(uniCode));
}
}
return buffer.toString();
} /**
 * 获取一个汉字的拼音首字母。 GB码两个字节分别减去160,转换成10进制码组合就可以得到区位码
 * 例如汉字"你"的GB码是0xC4/0xE3,分别减去0xA0(160)就是0x24/0x43
 * 0x24转成10进制就是36,0x43是67,那么它的区位码就是3667,在对照表中读音为‘n'
 */ private static char convert(byte[] bytes) { char result = '-';
int secPosvalue = 0;
int i;
for (i = 0; i < bytes.length; i++) {
bytes[i] -= GB_SP_DIFF;
}
secPosvalue = bytes[0] * 100 + bytes[1];
for (i = 0; i < 23; i++) {
if (secPosvalue >= secPosvalueList[i]
&& secPosvalue < secPosvalueList[i + 1]) {
result = firstLetter[i];
break;
}
}
return result;
}

}

解决方案 »

  1.   

    答:我的想法是:
    同于你的convert(byte[] bytes)是基于GBK的byte[] bytes设计的,因此,
    你的getFirstLetter(String oriStr)方法中,这一句:
     byte[] uniCode = new String(temp).getBytes();
    得到的并不是UNICODE字节编码数据,而是平台默认的字节编码数据(对于WINDOWS,这是GBK,刚好与
    convert(byte[] bytes)的要求相一致,因而是没有问题的.而在LINUX平台,默认是UTF-8,故得到的UTF-8
    字节编码数据,把这个UTF-8字节数据传给要求GBK编码的convert(byte[] bytes),当然会乱码了.)因此:将byte[] uniCode = new String(temp).getBytes();
    强制改为:
    byte[] uniCode = new String(temp).getBytes("GBK");//强制形成GBK字节编码数据,传给convert
    试试.以上仅供你参考
      

  2.   

    就顶楼上的public static String getFirstLetter(String oriStr) {
           String str=new String(oriStr.getBytes(UTF-8),"gbk");
           .........    }