我无意看到
DataOutputStream的源码.结果发现这段.
/** * 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 counterout.writer((byte)s.charAt(i));//这个因为英文一个字节就够了,可中文是两个字节,结果我们的中文就在这里被扔掉一半.于是就再输出就乱码了. 相比之下:written
is incremented by the * length ofs
. * * @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); }
/** * Writes a string to the underlying output stream as a sequence of * characters. Each character is written to the data output stream as * if by the这个要好一点了,中文就可以真确的被写入了.writeChar
method. If no exception is * thrown, the counterwritten
is incremented by twice * the length ofs
. * * @param s aString
value to be written. * @exception IOException if an I/O error occurs. * @see java.io.DataOutputStream#writeChar(int) * @see java.io.FilterOutputStream#out */ public final void writeChars(String s) throws IOException { int len = s.length(); for (int i = 0 ; i < len ; i++) { int v = s.charAt(i); out.write((v >>> 8) & 0xFF); out.write((v >>> 0) & 0xFF); } incCount(len * 2); }