public final char readChar() throws IOException {
int ch1 = in.read();
int ch2 = in.read();
if ((ch1 | ch2) < 0)
throw new EOFException();
return (char)((ch1 << 8) + (ch2 << 0));
}这是DataInputStream的readChar()源码,请高手解释一下后三句的作用,我知道"|"是或运算,也知道"<<"是左移位,我不是要解释语句的意思,我要知道为什么要这样做才实现readChar()的功能.
int ch1 = in.read();
int ch2 = in.read();
if ((ch1 | ch2) < 0)
throw new EOFException();
return (char)((ch1 << 8) + (ch2 << 0));
}这是DataInputStream的readChar()源码,请高手解释一下后三句的作用,我知道"|"是或运算,也知道"<<"是左移位,我不是要解释语句的意思,我要知道为什么要这样做才实现readChar()的功能.
* 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;
可以看出in.read()读出一个byte。而一个char是由两个byte组成,所以c1保存高位的字节,c2保存地位字节, (char)((ch1 << 8) + (ch2 << 0));是将c1,c2组合到一起成为一个char
至于 | 问题,用 |的只用了三条指令
iload_2
iload_3
ior, 而如果这样实现的话 if ((ch1==-1 || ch2==-1))指令就多了
iload_2
iconst_m1
if_icmpeq 20
iload_3
iconst_m1
if_icmpne 28