这里说明两三个实例,后面的看源代码就很清晰了。
1.readBoolean()
public final boolean readBoolean() throws IOException {
int ch = in.read();
if (ch < 0)
throw new EOFException();
return (ch != 0);
}
由于DataInputStream是FilterInputStream,所以里面有一个基本流 in,首先调用in.read()方法
在java.io.InputStream类的read()的API说明:
/**
* Reads the next byte of data from the input stream. The value byte is
* returned as an <code>int</code> in the range <code>0</code> to
* <code>255</code>. If no byte is available because the end of the stream
* has been reached, the value <code>-1</code> is returned. This method
* blocks until input data is available, the end of the stream is detected,
* or an exception is thrown.
*
* <p> A subclass must provide an implementation of this method.
*
* @return the next byte of data, or <code>-1</code> if the end of the
* stream is reached.
* @exception IOException if an I/O error occurs.
*/
public abstract int read() throws IOException;
他将返回一个介于0-255的int值。假设欲读取的字节是0x80,对应的byte值为-128,但是返回的应该是128。
从另一个角度讲,byte值完全可能为-1,但是-1是作为已读取完的标记,这两者肯定不能混,所以是采用了返回0-255对应byte的-128 - 127的机制
参考java.io.ByteArrayInputStream的read()方法的实现:
public synchronized int read() {
return (pos < count) ? (buf[pos++] & 0xff) : -1;
}
buf是一个byte[]数组,注意后面的&0xff,将搞24位丢弃,即肯定是一个0到255的树
(PS:有关Java中byte和short其实是由int存储的机制不予考虑,所以整篇文章可能不严谨,主要是为了方便理解)
返回到readBoolean方法,这时就很明显了,检查EOF边界,然后判断等不等于0,返回。
可见readBoolean其实的机制就是,如果流的下一个字节为0x00则为false,其余255种情况为true
2. readByte()
由于是JDK的源码我就不再继续贴了,自己看就行了($JDK_HOME/src.zip)
假设流的下一个字节是0xFF,那么in.read()返回了255,然后强制转回到byte型就是-1了(截取高24位)
3.readUnsignedByte()
与readByte()不同的是,其对in.read()返回的int不做处理,直接返回。
这个方法的意思就很明显了,读取流的一个字节,返回一个无符号byte(0-255),只不过Java不像C那样有unsigned型,所以直接返回个int了。这个int只会是0-255
4.readShort()和readUnsignedShort()
注意判断EOF条件是ch1 | ch2 < 0。因为in.read()如果没有EOF越界时,是返回0-255的int,这个int最高位是0。
所以只有ch1和ch2都是介于0-255(未EOF越界)时,他们或运算才会>=0,最高位为0。
同理二者只要有一个为-1,那么或运算肯定<0,抛EOFException
5.readLong()
这里有点特殊,是读取八个字节的数据到readbuffer数组里去,然后做处理,readFully会检查EOF。
6.readFloat和readDouble
不解释了,IEEE 754标准