zoukankan      html  css  js  c++  java
  • DataOutputStream的writeBytes(String s)


    最近,在关于网络请求中有用到DataOutputStraem中的writeBytes()方法,然而就是这个问题,导致了传输中文时就出现问题,着实困扰了很长一段时间。
    后来,服务器端同事建议我使用DataOutputStream.write(byte[])方法,发现问题解决了。起初认为是编码问题,后来认真研究了一下,发现了问题的原因。

    首先,先看一下DataOutputStream的writeBytes方法的实现。


    /**
         * Writes out the string to the underlying output stream as a 
         * sequence of bytes. Each character in the string is written out, in 
         * sequence, by discarding its high eight bits. If no exception is 
         * thrown, the counter <code>written</code> is incremented by the 
         * length of <code>s</code>.
         *
         * @param      s   a string of bytes to be written.
         * @exception  IOException  if an I/O error occurs.
         * @see        java.io.FilterOutputStream#out
         */
     
     public final void writeBytes(String s) throws IOException {
    	int len = s.length();
    	for (int i = 0 ; i < len ; i++) {
    	    out.write((byte)s.charAt(i));
    	}
    	incCount(len);
        }


    问题出现了,int len = s.length();这就验证了问题的表象,对于英文的字符串都是正常的,对于某些中文就出现问题了。
    这个writeBytes的方法,对于单字节的文字(多为英文)是没有问题的,因为当单字节是string.length()和string.getBytes().length是相同的,而多字节不同。
    所以,对于存在多字节的请求,不要使用writeBytes(String)的方法,推荐使用write(byte[])等方法

  • 相关阅读:
    学习一波cmd
    青春,就是用來懷念的
    菜鸟的 linux 学习笔记 -- OOM
    python 获取本机 IP
    win8防火墙配置出站规则禁止QQ访问
    netsh配置Windows防火墙(advfirewall)
    TCP/IP协议
    TCP的状态 (SYN, FIN, ACK, PSH, RST, URG)
    Address already in use: AH00072: make_sock: could not bind to address 0.0.0.0:80
    Photoshop  cs6 快捷键命令大全
  • 原文地址:https://www.cnblogs.com/jiangu66/p/3172266.html
Copyright © 2011-2022 走看看