zoukankan      html  css  js  c++  java
  • 【GBK、UTF-8、ISO8859-1】三种编码方式总结及实例

      感谢:https://blog.csdn.net/youngstar70/article/details/64117297

     一、总结

     在Java中,String的getBytes()方法是得到一个操作系统默认的编码格式的字节数组。这个表示在不同情况下,返回的东西不一样! 

      String.getBytes(String decode)方法会根据指定的decode编码返回某字符串在该编码下的byte数组表示,如:

    byte[] b_gbk = "深".getBytes("GBK");   //b_gbk的长度为2
    byte[] b_utf8 = "深".getBytes("UTF-8");   //b_utf8的长度为3
    byte[] b_iso88591 = "深".getBytes("ISO8859-1");//   b_iso88591的长度为1
    byte[] b_unicode = "深".getBytes("unicode");  //b_unicode长度为4

     

      将分别返回“深”这个汉字在GBK、UTF-8、ISO8859-1和unicode编码下的byte数组表示,此时b_gbk的长度为2,b_utf8的长度为3,b_iso88591的长度为1,unicode为4。 

     

      而与getBytes相对的,可以通过new String(byte[], decode)的方式来还原这个“深”字时,这个new String(byte[], decode)实际是使用decode指定的编码来将byte[]解析成字符串

    String s_gbk = new String(b_gbk,"GBK");   
    String s_utf8 = new String(b_utf8,"UTF-8");   
    String s_iso88591 = new String(b_iso88591,"ISO8859-1");   
    String s_unicode = new String(b_unicode, "unicode");  

      通过打印s_gbk、s_utf8、s_iso88591和unicode,会发现,s_gbk、s_utf8和unicode都是“深”,而只有s_iso88591是一个不认识的字符,为什么使用ISO8859-1编码再组合之后,无法还原“深”字呢,其实原因很简单,因为ISO8859-1编码的编码表中,根本就没有包含汉字字符,当然也就无法通过"深".getBytes("ISO8859-1");来得到正确的“深”字在ISO8859-1中的编码值了,所以再通过new String()来还原就无从谈起了。 

      因此,通过String.getBytes(String decode)方法来得到byte[]时,一定要确定decode的编码表中确实存在String表示的码值,这样得到的byte[]数组才能正确被还原。 

      有时候,为了让中文字符适应某些特殊要求(如http header头要求其内容必须为iso8859-1编码),可能会通过将中文字符按照字节方式来编码的情况,如 

      String s_iso88591 = new String("深".getBytes("UTF-8"),"ISO8859-1"), 

      这样得到的s_iso8859-1字符串实际是三个在 ISO8859-1中的字符,在将这些字符传递到目的地后,目的地程序再通过相反的方式String s_utf8 = new String(s_iso88591.getBytes("ISO8859-1"),"UTF-8")来得到正确的中文汉字“深”。这样就既保证了遵守协议规定、也支持中文。 

      同样,在开发会检查字符长度,以免数据库字段的长度不够而报错,考虑到中英文的差异,肯定不能用String.length()方法判断,而需采用String.getBytes().length;

      而这方法将返回该操作系统默认的编码格式的字节数组。如字符串“Hello!你好!”,在一个中文WindowsXP系统下,结果为12,而在英文的UNIX环境下,结果将为9。

      因为该方法和平台(编码)相关的。

      在中文操作系统中,getBytes方法返回的是一个GBK或者GB2312的中文编码的字节数组,其中中文字符,各占两个字节。

      而在英文平台中,一般的默认编码是"ISO-8859-1",每个字符都只取一个字节(而不管是否非拉丁字符)。所以在这种情况下,应该给其传入字符编码字符串,即String.getBytes("GBK").length。

    二、main方法测试

     

    public static void main(String[] args) {
            String testData = "123abc数据";
            //此次测试前提:参数包含中文
            testU8(testData);//UTF_8-String:123abc数据
            testIso(testData);//ISO_8859_1-String:123abc??
            testChineseTrue(testData);//test3-String:123abc数据
            testChineseFalse(testData);//test4-String:123abc??
        }
        
        /**
         * 正常返回:UTF_8-String:123abc数据
         * @param testdata
         */
        public static void testU8(String testdata){
            byte[] bytes = testdata.getBytes(CharsetUtil.UTF_8);
            String result = new String(bytes,CharsetUtil.UTF_8);
            System.out.println("UTF_8-String:"+result);
        }
        /**
         * 返回有乱码:123abc??
         * 原因:ISO8859-1编码的编码表中,根本就没有包含汉字字符。
         * @param testdata
         */
        public static void testIso(String testdata){
            byte[] bytes = testdata.getBytes(CharsetUtil.ISO_8859_1);
            String result = new String(bytes,CharsetUtil.ISO_8859_1);
            System.out.println("ISO_8859_1-String:"+result);
        }
        /**
         * 返回:123abc数据
         * 通过String.getBytes(String decode)方法来得到byte[]时,一定要确定decode的编码表中确实存在String表示的码值。
         * gbk/utf-8都可以
         * @param testdata
         */
        public static void testChineseTrue(String testdata){
            Object message = null;
            message = new String(testdata.getBytes(CharsetUtil.GBK),CharsetUtil.ISO_8859_1);
            String returnData = message.toString();
            //解析
            byte[] xmlByte =returnData.getBytes(CharsetUtil.ISO_8859_1);
            String xml = "";
            xml = new String(xmlByte,CharsetUtil.GBK);
            System.out.println("test3-String:"+xml);
        }
        
        /**
         * 当传入的参数包含中文时,执行该方法出现乱码。 返回:test4-String:123abc??
         * 原因:通过String.getBytes(String decode)方法来得到byte[]时,一定要确定decode的编码表中确实存在String表示的码值。
         * 而ISO8859-1编码的编码表中,根本就没有包含汉字字符。
         * @param testdata
         */
        public static void testChineseFalse(String testdata){
            Object message = null;
            message = new String(testdata.getBytes(CharsetUtil.ISO_8859_1),CharsetUtil.GBK);
            String returnData = message.toString();
            //解析
            byte[] xmlByte =returnData.getBytes(CharsetUtil.GBK);
            String xml = "";
            xml = new String(xmlByte,CharsetUtil.ISO_8859_1);
            System.out.println("test4-String:"+xml);
        }

     

    三、本地代码解析:

        //将接收到的message编码后传送给后台
        public ChannelBuffer encode(Object message) throws TransportCodecException {
            try{
                //message虽说是Object类型,看不到具体类型,但debug知道其数据格式为byte[],字节数组形式,可以强转为byte[],然后再通过New String(byte[],charset)方法将byte[]转换为String类型
                //因为不确定接收到的message是什么编码格式,这里会统一转成gbk编码。
                message = new String((byte[])message,CharsetUtil.GBK);
                String gbkMessage = message.toString();
                
                //当计算字段长度时,由于中英文的差异,肯定不能用String.length()方法判断,而需采用String.getBytes().length;
                byte[] arrayOfByte = gbkMessage.getBytes(CharsetUtil.GBK);
                String requestByte = String.valueOf(arrayOfByte.length);
                String request = StringUtils.leftPad(requestByte,6,"0") + gbkMessage;
                
                LogConsole.info("xxx request message: " + request);
                return ChannelBuffers.copiedBuffer(request.getBytes(CharsetUtil.GBK)); //
            }
            catch(Exception e){
            }
            return null;
        }
        //解析接收后台的报文,后台中文是用utf-8编码的,然后整体用iso再封一次。
        //所以我们接收到后,会先用iso解下,decode方法返回的数据格式是byte[],再通过new String(xmlByte,CharsetUtil.UTF_8)将其按照utf-8解析。
        public Object decode(ChannelBuffer buffer) throws TransportCodecException {
            //ChannelBuffer该类型是本系统自己封装,通过该方法将ChannelBuffer转换为String类型,这时候的中文还是乱码,之后会用utf-8解下。
            String _message = buffer.toString(CharsetUtil.ISO_8859_1);
            
            if (_message.length() <= 0){
                return null;
            }
            
            if (isDirect){
                return buffer;
            }
            else{
                if (exchangeLength == -1){
                    exchangeLength = fixedLength(_message,buffer);//后台返回报文格式为:6位的长度位+完整报文,该方法是处理长度位
                }
                
                int readableLength = buffer.readableBytes();
                if (hasRemaining(readableLength)){
                    clear();
                    LogConsole.info("xxx response message:" + _message);
                    return _message.substring(fixedLength).getBytes(CharsetUtil.ISO_8859_1);
                }
                
                return null;
            }
        }
        //byte[]转String
        xml = new String(xmlByte,CharsetUtil.UTF_8);

     

     

     

     

     

     

     

  • 相关阅读:
    UDP通信网络编程
    多线程:购票小案例
    多线程:线程池异步计算,2个线程,1个计算10的阶乘,一个计算20的阶乘并返回
    Kong入门指南
    5分钟完成App后端API开发
    Docker安装Kong
    React Native如何用调用RestFul API
    Flutter如何用调用RestFul API
    如何用Flutter调用生成的RestFul API
    自动化API之一 生成开源ERP Odoo App 的RestFul API
  • 原文地址:https://www.cnblogs.com/amunamuna/p/8922125.html
Copyright © 2011-2022 走看看