native 2 ascii符号化変換

2606 ワード

package com.test;

public class Test2 {

	public static void main(String argv[]) {

		Test2 tt = new Test2();
		String str1 = tt.native2ascii("Jenkins ");
		System.out.println(str1);
		String str2 = tt
				.ascii2native("\u542F\u52A8\u5B8C\u6210\u540E\u6D4F\u89C8\u5668\u5C06\u81EA\u52A8\u5237\u65B0");
		System.out.println(str2);

	}

	public String native2ascii(String str) {

		char ac[] = str.toCharArray();

		int len = ac.length;

		StringBuffer out = new StringBuffer();

		for (int i = 0; i < len; i++)

			if (ac[i] > '\177') {

				out.append(new char[] { 92, 117 });

				String s1 = Integer.toHexString(ac[i]);

				StringBuffer stringbuffer = new StringBuffer(s1);

				stringbuffer.reverse();

				int l = 4 - stringbuffer.length();

				for (int i1 = 0; i1 < l; i1++)

					stringbuffer.append('0');

				for (int j1 = 0; j1 < 4; j1++)

					out.append(stringbuffer.charAt(3 - j1));

			} else {

				out.append(ac[i]);

			}

		return out.toString();

	}

	public String ascii2native(String str) {

		char[] ac1 = str.toCharArray();

		int k = ac1.length;

		int l = 0;

		boolean flag = false;

		boolean flag1 = false;

		StringBuffer sb = new StringBuffer();

		int k1 = 0;

		do {

			if (k1 >= k)

				break;

			char c = ac1[k1++];

			if (c != '\\' || k - k1 < 5) {

				sb.append(c);

				continue;

			}

			c = ac1[k1++];

			if (c != 'u') {

				sb.append('\\');

				sb.append(c);

			} else {

				char c1 = '\0';

				boolean flag2 = true;

				try {

					c1 = (char) Integer.parseInt(new String(ac1, k1, 4), 16);

				} catch (NumberFormatException numberformatexception) {

					flag2 = false;

				}

				if (flag2) {

					sb.append(c1);

					k1 += 4;

				} else {

					sb.append('\\');

					sb.append(c);

				}

			}

		} while (true);

		return sb.toString();

	}

}