📅  最后修改于: 2023-12-03 14:42:14.675000             🧑  作者: Mango
在Java IO中,PushbackInputStream
类允许程序读取缓冲区之前的字节,并将该字节推回输入流中。这使得我们可以读取上一个字符,例如在需要确定 token(标记)类型的情况下。
public PushbackInputStream(InputStream in)
public PushbackInputStream(InputStream in, int size)
以下是 PushbackInputStream
常用的方法:
public void unread(int b) throws IOException
public void unread(byte[] b) throws IOException
public void unread(byte[] b, int off, int len) throws IOException
unread()
方法可用于推回多个字节。public int read() throws IOException
public int read(byte[] b, int off, int len) throws IOException
以下是 PushbackInputStream
的示例代码:
import java.io.*;
public class PushbackInputStreamDemo {
public static void main(String[] args) {
String str = "hello world";
byte[] buffer = str.getBytes();
ByteArrayInputStream inputStream = new ByteArrayInputStream(buffer);
PushbackInputStream pushbackInputStream = new PushbackInputStream(inputStream, 2);
try {
int val = 0;
while ((val = pushbackInputStream.read()) != -1) {
System.out.print((char) val);
if (val == 'o') {
pushbackInputStream.unread(val);
val = pushbackInputStream.read();
System.out.print((char) val);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
以上代码将输出 "hellolo world"。在输入流读取到 "o" 时,程序将 "o" 退回输入流,读取前一个字符并打印。