当前位置:编程学习 > JAVA >>

UCS2转UTF-8方法

     前两天工作时需要将UCS2编码转为UTF-8编码在网页显示。网上找了好久没有好方法,后来还是同事给了一个自己的函数,顺利解决问题。把函数贴在这里,愿帮助遇到同样问题的工友们~

/**
     * UCS2转码为utf-8
     *
     * @author Shangxj
     * @param theString
     * @return String
     */
    public static String UCS2ToUtf8(String theString) {

        // 对theString参数进行处理
        String strU = "\\u";
        String resultStr = "";
        int j = 0;
        int length = theString.trim().length();
        StringBuffer outBuffer = new StringBuffer(length);

        try {
            if (!(theString == null || theString.trim().equals(""))) {

                for (int i = -4; i < length - 4; i = i + 4) {
                    String temStr = theString.trim().substring(i + 4, j + 4);
                    resultStr = resultStr + strU + temStr;
                    j = j + 4;
                }
                char aChar;
                int len = resultStr.length();
                for (int x = 0; x < len;) {
                    aChar = resultStr.charAt(x++);
                    if (aChar == '\\') {
                        aChar = resultStr.charAt(x++);
                        if (aChar == 'u') {
                            // Read the xxxx
                            int value = 0;
                            for (int i = 0; i < 4; i++) {
                                aChar = resultStr.charAt(x++);
                                switch (aChar) {
                                case '0':
                                case '1':
                                case '2':
                                case '3':
                                case '4':
                                case '5':
                                case '6':
                                case '7':
                                case '8':
                                case '9':
                                    value = (value << 4) + aChar - '0';
                                    break;
                                case 'A':
                                case 'B':
                                case 'C':
                                case 'D':
                                case 'E':
                                case 'F':
                          

补充:软件开发 , Java ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,