现在的位置: 首页 > 综合 > 正文

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

2013年09月07日 ⁄ 综合 ⁄ 共 1426字 ⁄ 字号 评论关闭

//转为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();
 }

【上篇】
【下篇】

抱歉!评论已关闭.