Java.io.PushbackInputStream.read() 方法
描述
java.io.PushbackInputStream.read() 方法从此输入流中读取数据的下一个字节。 值字节作为 int 返回,范围为 0 到 255。如果由于到达流的末尾而没有可用的字节,则返回值 -1。 此方法会一直阻塞,直到输入数据可用、检测到流结束或引发异常。
此方法返回最近推回的字节(如果有),否则调用其底层输入流的 read 方法并返回该方法返回的任何值。
声明
以下是 java.io.PushbackInputStream.read() 方法的声明。
public int read()
参数
NA
返回值
此方法返回数据的下一个字节,如果已到达流的末尾,则返回 -1。
异常
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 from the buffer one character at a time
for (int i = 0; i < byteArray.length; i++) {
// read a char into our array
arrByte[i] = (byte) pis.read();
// display the read byte
System.out.print((char) arrByte[i]);
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
让我们编译并运行上面的程序,这将产生下面的结果 −
Hello

