int read(byte[] b, int off, int len)
描述 (Description)
java.io.PushbackInputStream.read(byte[] b,int off,int len)方法将此输入流中最多len个字节的数据读入一个字节数组。 该方法首先读取任何推回的字节; 之后,如果读取的字节数少于len个字节,则从基础输入流中读取。 如果len不为零,则该方法将阻塞,直到至少有1个字节的输入可用; 否则,不读取任何字节,返回0。
声明 (Declaration)
以下是java.io.PushbackInputStream.read()方法的声明。
public int read(byte[] b,int off,int len)
参数 (Parameters)
b - 读取数据的缓冲区。
off - 目标数组中的起始偏移量b。
len - 读取的最大字节数。
返回值 (Return Value)
此方法返回读入缓冲区的总字节数,如果没有更多数据,则返回-1,因为已到达流的末尾。
异常 (Exception)
NullPointerException - 如果b为null。
IndexOutOfBoundsException - 如果off为负数,则len为负数,或len为b.length-off。
IOException - 如果通过调用close()方法关闭此输入流,或发生I/O错误。
例子 (Example)
以下示例显示了java.io.PushbackInputStream.read()方法的用法。
package com.iowiki;
import java.io.*;
public class PushbackInputStreamDemo {
public static void main(String[] args) {
// declare a buffer and initialize its size:
byte[] arrByte = new byte[1024];
// create an array for our message
byte[] byteArray = new byte[]{'H', 'e', 'l', 'l', 'o'};
// create object of PushbackInputStream class for specified stream
InputStream is = new ByteArrayInputStream(byteArray);
PushbackInputStream pis = new PushbackInputStream(is);
try {
// read a char into our array
pis.read(arrByte, 0, 3);
// print arrByte
for (int i = 0; i < 3; i++) {
System.out.print((char) arrByte[i]);
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
让我们编译并运行上面的程序,这将产生以下结果 -
Hel