InputStream中read()与read(byte[] b) 用法介绍

来源:互联网 发布:淘宝店铺卖鞋名字大全 编辑:程序博客网 时间:2024/05/22 00:31

read() :  从输入流中读取数据的下一个字节,返回0到255范围内的int字节值。如果因为已经到达流末尾而没有可用的字节,则返回-1。在输入数据可用前此方法阻塞,检测到流末尾或者抛出异常此方法结束。

read(byte[] b) : 从输入流中读取一定数量的字节,并将其存储在缓冲区数组 b 中。以整数形式返回实际读取的字节数。在输入数据可用前此方法阻塞,检测到流末尾或者抛出异常此方法结束。

如果 b 的长度为 0,则不读取任何字节并返回 0;否则,尝试读取至少一个字节。如果因为流位于文件末尾而没有可用的字节,则返回值 -1;否则,至少读取一个字节并将其存储在 b 中。

将读取的第一个字节存储在元素 b[0] 中,下一个存储在 b[1] 中,依次类推。读取的字节数最多等于 b 的长度。设 k 为实际读取的字节数;这(www.111cn.net)些字节将存储在 b[0] 到 b[k-1] 的元素中,不影响 b[k] 到 b[b.length-1] 的元素。

 

由帮助文档中的解释可知,read()方法每次只能读取一个字节,所以也只能读取由ASCII码范围内的一些字符。这些字符主要用于显示现代英语和其他西欧语言。而对于汉字等unicode中的字符则不能正常读取。只能以乱码的形式显示。(说的好像不对吧,read(byte[] b)好像也不能保证读取的字节数是偶数)

对于read()方法的上述缺点,在read(byte[] b)中则得到了解决,就拿汉字来举例,一个汉字占有两个字节,则可以把参数数组b定义为大小为2的数组即可正常读取汉字了。当然b也可以定义为更大,比如如果b=new byte[4]的话,则每次可以读取两个汉字字符了,但是需要注意的是,如果此处定义b 的大小为3或7等奇数,则对于全是汉字的一篇文档则不能全部正常读写了。


public int read(byte[] b)         throws IOException
Reads some number of bytes from the input stream and stores them into the buffer arrayb. The number of bytes actually read is returned as an integer. This method blocks until input data is available, end of file is detected, or an exception is thrown.

If the length of b is zero, then no bytes are read and 0 is returned; otherwise, there is an attempt to read at least one byte. If no byte is available because the stream is at the end of the file, the value-1 is returned; otherwise, at least one byte is read and stored intob.

The first byte read is stored into element b[0], the next one intob[1], and so on. The number of bytes read is, at most, equal to the length ofb. Let k be the number of bytes actually read; these bytes will be stored in elementsb[0] through b[k-1], leaving elementsb[k] through b[b.length-1] unaffected.

The read(b) method for class InputStream has the same effect as:

 read(b, 0, b.length) 

Parameters:
b - the buffer into which the data is read.
Returns:
the total number of bytes read into the buffer, or -1 is there is no more data because the end of the stream has been reached.
Throws:
IOException - If the first byte cannot be read for any reason other than the end of the file, if the input stream has been closed, or if some other I/O error occurs.
NullPointerException - ifb is null.

0 0
原创粉丝点击