zoukankan      html  css  js  c++  java
  • java中文和unicode编码相互转换(转)

     1 import java.io.UnsupportedEncodingException;
     2 
     3 public class TestUnicode{
     4 
     5     public static void main(String[] args) throws UnsupportedEncodingException {
     6         String s = "简介";
     7         System.out.println(s+" --的unicode编码是:"+gbEncoding(s));
     8         System.out.println(gbEncoding(s) + " --转换成中文是:"+decodeUnicode(gbEncoding(s)));
     9         
    10         //System.out.println(gbEncoding(s) + " --转换成中文是:"+decodeUnicode("\u7b80\u4ecb"));
    11     }
    12     
    13     /*
    14      * 中文转unicode编码
    15      */
    16     public static String gbEncoding(final String gbString) {
    17         char[] utfBytes = gbString.toCharArray();
    18         String unicodeBytes = "";
    19         for (int i = 0; i < utfBytes.length; i++) {
    20             String hexB = Integer.toHexString(utfBytes[i]);
    21             if (hexB.length() <= 2) {
    22                 hexB = "00" + hexB;
    23             }
    24             unicodeBytes = unicodeBytes + "\u" + hexB;
    25         }
    26         return unicodeBytes;
    27     }
    28     /*
    29      * unicode编码转中文
    30      */
    31     public static String decodeUnicode(final String dataStr) {
    32         int start = 0;
    33         int end = 0;
    34         final StringBuffer buffer = new StringBuffer();
    35         while (start > -1) {
    36             end = dataStr.indexOf("\u", start + 2);
    37             String charStr = "";
    38             if (end == -1) {
    39                 charStr = dataStr.substring(start + 2, dataStr.length());
    40             } else {
    41                 charStr = dataStr.substring(start + 2, end);
    42             }
    43             char letter = (char) Integer.parseInt(charStr, 16); // 16进制parse整形字符串。
    44             buffer.append(new Character(letter).toString());
    45             start = end;
    46         }
    47         return buffer.toString();
    48     }
    49 }
  • 相关阅读:
    XRTable 表新增列和行数据
    sql server 清理数据库日志
    C# 数字 转换 大写汉字
    NavBarControl 简单配置
    bandedGridView
    TileView 基本配置
    CardView 基本配置
    ButtonEdit 参数配置
    无边框窗体,鼠标移动窗体
    【网站】windows phpstudy v8.1搭建https
  • 原文地址:https://www.cnblogs.com/vianzhang/p/8399550.html
Copyright © 2011-2022 走看看