Java tutorial
//package com.java2s; /** * Copyright (C) 2009-2011 Jack A. Rider All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ public class Main { public static String toUnicode(String input) { StringBuffer ret = new StringBuffer(); if (input != null) { for (int i = 0; i < input.length(); i++) { char ch = input.charAt(i); if (!Character.isWhitespace(ch) && ch < 0x20 || ch > 0x7e) { ret.append("\\u"); // requires 1.5 VM // ret.append(String.format("%1$04x", new Object[] { Integer.valueOf(ch) })); ret.append(leading4Zeros(Integer.toHexString(ch))); } else { ret.append(ch); } } } return ret.toString(); } /** * @param hexString max 4 characters length * @return same string with leading zeros */ public static char[] leading4Zeros(String hexString) { char[] chars = "0000".toCharArray(); int length = hexString.length(); hexString.getChars(0, length, chars, 4 - length); return chars; } }