java.io.ByteArrayInputStream.read(byte[] b, int off, int len) 方法读取当前输入流中的数据的len个字节到字节数组。read()方法不会进入阻塞。 更多教程请访问http://www.manongzj.com
声明
以下是java.io.ByteArrayInputStream.read(byte[] b, int off, int len) 方法的声明:
public int read(byte[] b, int off, int len)
参数
-
b -- 数据被读入该缓冲
-
off -- 在目标数组b的偏移开始位置
-
len -- 读取的最大字节数
返回值
读入缓冲区的字节数。返回-1,如果流已经达到了结束位置。
异常
-
NullPointerException -- 如是 b 为 null.
-
IndexOutOfBoundsException -- 如果len大于输入流的偏移量length后,off为负,或len为负。
例子
下面的例子显示java.io.ByteArrayInputStream.read(byte[] b, int off, int len) 方法。
package com.yiibai;
import java.io.ByteArrayInputStream;
import java.io.IOException;
public class ByteArrayInputStreamDemo {
public static void main(String[] args) throws IOException {
byte[] buf = {65, 66, 67, 68, 69};
ByteArrayInputStream bais = null;
try{
// create new byte array input stream
bais = new ByteArrayInputStream(buf);
// create buffer
byte[] b = new byte[4];
int num = bais.read(b, 2, 2);
// number of bytes read
System.out.println("Bytes read: "+num);
// for each byte in a buffer
for (byte s :b)
{
// covert byte to char
char c = (char)s;
// prints byte
System.out.print(s);
if(s==0)
// if byte is 0
System.out.println(": Null");
else
// if byte is not 0
System.out.println(": "+c);
}
}catch(Exception e){
// if I/O error occurs
e.printStackTrace();
}finally{
if(bais!=null)
bais.close();
}
}
}
让我们来编译和运行上面的程序,这将产生以下结果:
Bytes read: 2
0: Null
0: Null
65: A
66: B