read()返回值问题
问题1:为啥io流里read()方法返回值范围0~255?
0到255是ascii码值(十进制),比如读文件里的1,那么返回码值49
如果需要将码值转换为字符,做个强制转换char
问题2:read方法定义,字节流读取文件,每调一次只读取一个字节,读取到的byte字节,为何返回int整型?
猜测是底层做了转换,为了跟ascii码对照,所以返回值将-128到0的范围转换为128到255
毕竟如果返回一个负数,在码表上没法转换为字符,对实际应用来说没意义。
/**
* 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;
浙公网安备 33010602011771号