您的位置:首页 > 其它

将中文转为unicode 及转回中文函数

2006-03-10 17:03 309 查看
/转为unicode
public static void writeUnicode(final DataOutputStream out, final String value) {
try {
final String unicode = gbEncoding( value );
final byte[] data = unicode.getBytes();
final int dataLength = data.length;

System.out.println( "Data Length is: " + dataLength );
System.out.println( "Data is: " + value );
out.writeInt( dataLength ); //先写出字符串的长度
out.write( data, 0, dataLength ); //然后写出转化后的字符串
} catch (IOException e) {

}
}

public static String gbEncoding( final String gbString ) {
char[] utfBytes = gbString.toCharArray();
String unicodeBytes = "";
for( int byteIndex = 0; byteIndex < utfBytes.length; byteIndex ++ ) {
String hexB = Integer.toHexString( utfBytes[ byteIndex ] );
if( hexB.length() <= 2 ) {
hexB = "00" + hexB;
}
unicodeBytes = unicodeBytes + "////u" + hexB;
}
System.out.println( "unicodeBytes is: " + unicodeBytes );
return unicodeBytes;
}

/*****************************************************
* 功能介绍:将unicode字符串转为汉字
* 输入参数:源unicode字符串
* 输出参数:转换后的字符串
*****************************************************/
private String decodeUnicode( final String dataStr ) {
int start = 0;
int end = 0;
final StringBuffer buffer = new StringBuffer();
while( start > -1 ) {
end = dataStr.indexOf( "////u", start + 2 );
String charStr = "";
if( end == -1 ) {
charStr = dataStr.substring( start + 2, dataStr.length() );
} else {
charStr = dataStr.substring( start + 2, end);
}
char letter = (char) Integer.parseInt( charStr, 16 ); // 16进制parse整形字符串。
buffer.append( new Character( letter ).toString() );
start = end;
}
return buffer.toString();
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: