int read(byte[] b, int off, int len)
描述 (Description)
java.io.ByteArrayInputStream.read(byte[] b, int off, int len)方法将此输入流中的len个字节数据读入一个字节数组。 read()方法不会阻塞。
声明 (Declaration)
以下是java.io.ByteArrayInputStream.read(byte[] b, int off, int len)方法的声明 -
public int read(byte[] b, int off, int len)
参数 (Parameters)
b - 将数据读入此缓冲区
off - 从目标阵列b开始的偏移量
len - 读取的最大字节数
返回值 (Return Value)
读入缓冲区的字节数。 如果流已到达结束,则返回-1。
异常 (Exception)
NullPointerException - 如果b为null。
IndexOutOfBoundsException - 如果len大于offset之后的输入流的长度,则off为负,或len为负。
例子 (Example)
以下示例显示了java.io.ByteArrayInputStream.read(byte [] b,int off,int len)方法的用法。
package com.iowiki;
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