escape Unicode String - Java java.lang

Java examples for java.lang:String Unicode

Description

escape Unicode String

Demo Code

/**/*from w w  w  . ja  v a2s . c  o  m*/
 * Copyright (c) 2009 DITA2InDesign project (dita2indesign.sourceforge.net)  Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at     http://www.apache.org/licenses/LICENSE-2.0  Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. 
 */
//package com.java2s;

public class Main {
    public static String escapeUnicodeString(String inString) {
        int l = inString.length();
        byte[] bytes = new byte[l];
        try {
            bytes = inString.getBytes("UTF16");
        } catch (Exception e) {
            System.err.println(e.getMessage());
        }
        String outString = "";
        byte zeroByte = new Byte("0").byteValue();
        byte lastByte = new Byte("127").byteValue();
        for (int i = 2; i < bytes.length; i = i + 2) {
            if ((bytes[i] == zeroByte) && (bytes[i + 1] <= lastByte)) {

                try {
                    String newString = new String(bytes, i + 1, 1);
                    outString = outString + newString;
                } catch (Exception e) {
                    System.err.println("escapeUnicodeString(): "
                            + e.getMessage());
                }
            } else {
                outString = outString + "\\u";
                outString = outString + byteToHex(bytes[i])
                        + byteToHex(bytes[i + 1]);
            }
        }
        return outString;
    }

    static public String byteToHex(byte b) {
        // Returns hex String representation of byte b
        char hexDigit[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8',
                '9', 'a', 'b', 'c', 'd', 'e', 'f' };
        char[] array = { hexDigit[(b >> 4) & 0x0f], hexDigit[b & 0x0f] };
        return new String(array);
    }
}

Related Tutorials