Chinaunix首页 | 论坛 | 博客
  • 博客访问: 102287
  • 博文数量: 21
  • 博客积分: 415
  • 博客等级: 一等列兵
  • 技术积分: 228
  • 用 户 组: 普通用户
  • 注册时间: 2011-07-11 12:17
文章分类

全部博文(21)

文章存档

2014年(1)

2012年(7)

2011年(13)

分类: Java

2011-07-13 15:43:52

最近在做一个开源的项目,里面涉及到了国际化,打开中文的配置文件,发现内容直接写成了Java Unicode的形式:/uXXXX的形式,没法看。顺手写了Unicode和文字相互转换的小程序,方便开发的进行。(程序没有健壮性,必须输入正确)

文字→Unicode

  1. package com.zsl;

  2. import java.util.Iterator;
  3. import java.util.Scanner;

  4. public class ZhToUnicode {
  5.     public static void main(String[] args) {
  6.         Scanner scanner=new Scanner(System.in);
  7.         String str;
  8.         char[] chars;
  9.         while(true){
  10.             str=scanner.next();    
  11.             chars=str.toCharArray();
  12.             for (char c : chars) {
  13.                 if(c<256){
  14.                     System.out.print("\\u00"+Integer.toHexString(c));
  15.                 }else if(c<4096){
  16.                     System.out.print("\\u0"+Integer.toHexString(c));
  17.                 }else{
  18.                     System.out.print("\\u"+Integer.toHexString(c));
  19.                 }
  20.             }
  21.             System.out.println();
  22.             System.out.flush();
  23.         }    
  24.     }
  25. }

Unicode→文字

  1. package com.zsl;

  2. import java.io.UnsupportedEncodingException;
  3. import java.util.Scanner;

  4. public class UnicodeToZh {
  5.     public static void main(String[] args) {
  6.         Scanner scan=new Scanner(System.in);
  7.         String unnicode;
  8.         String[] words;
  9.         while(true){
  10.             unnicode=scan.next();
  11.             words=unnicode.split("\\\\u");
  12.             
  13. //            for (String string : words) {

  14. //                System.out.println(string);

  15. //            }

  16.             for (String string : words) {
  17.                 
  18.                 if((string!=null)&&(string.length()>2)){
  19.                     int tmp=Integer.parseInt(string, 16);
  20.                     System.out.print((char)tmp);
  21. //                    System.out.println(string);

  22.                 }
  23.             }
  24.             System.out.println();
  25.         }
  26.     }
  27. }

 


阅读(1003) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~