native2ascii的 java实现

描述:简单模拟JDK自带的 native2ascii.exe 的功能

package org.demo.util;

import java.io.IOException;

/**
 * 字符转换
 * @author  
 * @date    2010-9-13
 * @file    org.demo.util.Ascii2Native.java
 */
public class Native2Ascii {
	private static final String PREFIX = "\\u"; 
	/**
	 * @param args
	 */
	public static void main(String[] args)throws IOException {		
		String str = "Welcome!我的朋友.";
		String ascii = native2ascii(str);
		System.out.println("ascii->\n" + ascii);
		// 
		String data = ascii2native(ascii);
		System.out.println("native->\n" + data);
	}
	/**
	 * native2ascii
	 * @param text
	 * @return
	 */
	public static String native2ascii(String text){
		StringBuilder sb = new StringBuilder();
		for (int i=0; i<text.length(); i++){
			char ch = text.charAt(i);
			String ascii = char2ascii(ch);
			sb.append(ascii);
		}
		return sb.toString();
	}
	/**
	 * char -> ascii
	 * @param ch
	 * @return
	 */
	private static String char2ascii(char ch) {
		if (ch < 256){
			return Character.toString(ch);
		}
		String hex = Integer.toHexString(ch);
		if (hex.length() < 4){
			hex = "0" + hex;
		}
		return PREFIX + hex;
	}
	/**
	 * native2ascii
	 * @param ascii
	 * @return
	 */
	public static String ascii2native(String text){
		StringBuilder sb = new StringBuilder();
		int start = 0;
		int idx = text.indexOf(PREFIX);
		while (idx != -1){
			// 上一个 Unicode 码与当前 Unicode 码之间的有效字符
			// eg: \u0101ABC\u0102 之间的ABC
			sb.append(text.substring(start, idx));
			// 转换当前 Unicode 码
			String ascii = text.substring(idx + 2,idx + 6);
			char ch = (char)Integer.parseInt(ascii,16);
			sb.append(ch);
			// 查找下一个 Unicode
			start = idx + 6;
			idx = text.indexOf(PREFIX,start);
		}
		// 结尾的有效字符
		sb.append(text.substring(start));
		return sb.toString();
	} 
}

 输出结果:

ascii->
Welcome!\u6211\u7684\u670b\u53cb.
native->
Welcome!我的朋友.

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值