看源码,调用的第一句就获取了长度 int utflen = in.readUnsignedShort(); 这个方法的Doc :
Reads two input bytes and returns an int value in the range 0 through
Let a be the first byte read and b be the second byte. The value returned is:
(((a & 0xff) << 8) | (b & 0xff)) This method is suitable for reading the bytes written by the writeShort method of interface DataOutput if the argument to writeShort was intended to be a value in the range 0 through 65535. Returns: the unsigned 16-bit value read. Throws: EOFException - if this stream reaches the end before reading all the
IOException - if an I/O error occurs.
readUTF的Doc:
Reads from the stream in a representation of a Unicode character string encoded in modified UTF-8 format; this string of characters is then returned as a String. The details of the modified UTF-8 representation are exactly the same as for the readUTF method of DataInput.
DataOutputStream
DataInputStream
实际上在调用
writeUTF
写入时jdk
内部有将字符串的字节数写入流中,读取时先读取到字节长度,按照指定的字节长度读取出相应的字符串。看源码,调用的第一句就获取了长度
int utflen = in.readUnsignedShort();
这个方法的Doc :
readUTF的Doc: