Java.io.PushbackInputStream.read() 方法
描述
java.io.PushbackInputStream.read(byte[] b,int off,int len) 方法从这个输入流中读取最多 len 个字节的数据到一个字节数组中。 此方法首先读取任何推回的字节; 之后,如果读取的字节数少于 len,则从底层输入流中读取。 如果 len 不为零,则该方法会阻塞,直到至少有 1 个字节的输入可用; 否则,不读取任何字节并返回 0。
声明
以下是 java.io.PushbackInputStream.read() 方法的声明。
public int read(byte[] b,int off,int len)
参数
b − 读取数据的缓冲区。
off − 目标数组 b 中的起始偏移量。
len − 读取的最大字节数。
返回值
此方法返回读入缓冲区的总字节数,如果由于已到达流的末尾而没有更多数据,则返回 -1。
异常
NullPointerException − 如果 b 为空。
IndexOutOfBoundsException − 如果 off 为负数,len 为负数,或者 len 大于 b.length - off。
IOException − 如果此输入流已通过调用其 close() 方法关闭,或者发生 I/O 错误。
示例
下面的例子展示了 java.io.PushbackInputStream.read() 方法的使用。
package com.tutorialspoint;
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

