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[])等方法

原文地址:https://www.cnblogs.com/jiangu66/p/3172266.html