utf To Unicode - Java Internationalization

Java examples for Internationalization:Charset

Description

utf To Unicode

Demo Code


//package com.java2s;

import java.lang.Character.UnicodeBlock;

public class Main {
    public static void main(String[] argv) throws Exception {
        String inStr = "java2s.com";
        System.out.println(utf8ToUnicode(inStr));
    }// www  .  jav a2 s  .  c  o  m

    public static String utf8ToUnicode(String inStr) {
        char[] myBuffer = inStr.toCharArray();

        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < inStr.length(); i++) {
            UnicodeBlock ub = UnicodeBlock.of(myBuffer[i]);
            if (ub == UnicodeBlock.BASIC_LATIN) {
                // 
                sb.append(myBuffer[i]);
            } else if (ub == UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS) {
                // 
                int j = (int) myBuffer[i] - 65248;
                sb.append((char) j);
            } else {
                // 
                short s = (short) myBuffer[i];
                String hexS = Integer.toHexString(s);
                if (hexS.length() > 4) {
                    hexS = hexS.replace("ffff", "");
                }
                String unicode = "\\u" + hexS;
                sb.append(unicode.toLowerCase());
            }
        }
        return sb.toString();
    }
}

Related Tutorials