Java.io.ByteArrayInputStream.read() 方法
描述
java.io.ByteArrayInputStream.read(byte[] b, int off, int len) 方法从这个输入流中读取 len 个字节的数据到一个字节数组中。 read() 方法不会阻塞。
声明
以下是 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 为空。
IndexOutOfBoundsException − 如果 len 在 offset 后大于输入流的长度,off 为负数,或者 len 为负数。
示例
下面的例子展示了 java.io.ByteArrayInputStream.read(byte[] b, int off, int len) 方法的使用。
package com.tutorialspoint;
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

