Welcome 微信登录

首页 / 软件开发 / JAVA / J2ME中有关手机中文传输问题的解决办法

J2ME中有关手机中文传输问题的解决办法2011-02-14服务器到客户端:

下面代码是服务器端把字符写到Client端,经过gbEncoding()方法,所有的字符编码成:uXXXX.

代码:

/**
* Write the String data
*
* @param out
* @param value
*/
public static void writeUnicode(final DataOutputStream out, final String value)
throws ActionException {
try {
final String unicode = StringFormatter.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) {
throw new ActionException( IMDefaultAction.class.getName(), e.getMessage() );
}
}

以下代码是gbEncoding()方法,把双字节字符转换成uXXXX,ASIIC码在前面补00。

代码:

/**
* This method will encode the String to unicode.
*
* @param gbString
* @return
*/
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;
}

在客户端收到服务器的数据,先将其一个一个字符解码。双字节显示正常。

代码:

**
* This method will decode the String to a recognized String
* in ui.
* @param dataStr
* @return
*/
private StringBuffer 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;
}