美文网首页
2018-08-02字符串与UTF-8之间的转换

2018-08-02字符串与UTF-8之间的转换

作者: IT烟酒僧 | 来源:发表于2018-08-02 16:55 被阅读6次

    java String 转utf-8编码

    /**
    * Get XML String of utf-8
    * 
    * @return XML-Formed string
    */
    public static String getUTF8XMLString(String xml) {
        // A StringBuffer Object
        StringBuffer sb = new StringBuffer();
        sb.append(xml);
        String xmString = "";
        String xmlUTF8="";
        try {
            xmString = new String(sb.toString().getBytes("UTF-8"));
            xmlUTF8 = URLEncoder.encode(xmString, "UTF-8");
            System.out.println("utf-8 编码:" + xmlUTF8) ;
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
             e.printStackTrace();
        }
             // return to String Formed
             return xmlUTF8;
    }
    

    utf-8转Java String

     /**
    * @param fromStr : 要转换的原始字符串
    * @return : 得到转换后的字符串
     */
    private String is(String fromStr) {
      StringBuffer stringBufferResult = new StringBuffer();
        for (int i = 0; i < fromStr.length(); i++) {
            char chr = fromStr.charAt(i);
            if (chr == '%') {
                StringBuffer stringTmp = new StringBuffer();
                stringTmp.append(fromStr.charAt(i + 1)).append(fromStr.charAt(i + 2));
            //转换字符,16进制转换成整型
                stringBufferResult.append((char) (Integer.valueOf(stringTmp.toString(), 16).intValue()));
                 i = i + 2;
                continue;
            }
            stringBufferResult.append(chr);
        }
    
        String newStr = null; //编码转换
        try {
            newStr = new String(stringBufferResult.toString().getBytes("Cp1252"), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
         }
        return newStr;
    }

    相关文章

      网友评论

          本文标题:2018-08-02字符串与UTF-8之间的转换

          本文链接:https://www.haomeiwen.com/subject/nvjsvftx.html