博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
将中文转为unicode 及转回中文函数
阅读量:4169 次
发布时间:2019-05-26

本文共 1551 字,大约阅读时间需要 5 分钟。

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

转载地址:http://cwyai.baihongyu.com/

你可能感兴趣的文章
android中使用TextView来显示某个网址的内容,使用<ScrollView>来生成下拉列表框
查看>>
andorid里关于wifi的分析
查看>>
Hibernate和IBatis对比
查看>>
Spring MVC 教程,快速入门,深入分析
查看>>
Android 的source (需安装 git repo)
查看>>
LOCAL_PRELINK_MODULE和prelink-linux-arm.map
查看>>
Ubuntu Navicat for MySQL安装以及破解方案
查看>>
java多线程中的join方法详解
查看>>
idea添加gradle模块报错The project is already registered
查看>>
在C++中如何实现模板函数的外部调用
查看>>
HTML5学习之——HTML 5 拖放
查看>>
HTML5学习之——HTML 5 Canvas vs. SVG
查看>>
HTML5学习之——HTML 5 应用程序缓存
查看>>
HTML5学习之——HTML 5 Web Workers
查看>>
HTML5学习之——HTML 5 Canvas
查看>>
HTML5学习之——HTML5 内联 SVG
查看>>
HTML5学习之——HTML 5 服务器发送事件
查看>>
SVG学习之——HTML 页面中的 SVG
查看>>
SVG 形状学习之——SVG圆形
查看>>
SVG 滤镜学习之——SVG 滤镜
查看>>