在 输入/输出流体系中,有两个特殊的流
PushbackInputStream
PushbackReader
方法:
void unread(byte[]/char[] buf) : 将一个字节或者字符数组内容推回到推回缓冲区中,从而可以重复读取刚刚读的内容
void unread(byte[]/char[] buf, int off, int len) : 将一个字节或者字符数组里从 off 开始,长度为 len 字节/字符的内容推回到推回缓冲区中,从而可以重复读刚刚的内容
void unread(int b) : 将一个字节或者字符数组推回到推回缓冲区里,从而可以读取刚刚读的内容
这两个输入流都带有一个推回缓冲区,当程序调用这两个输入流的 unread() 方法时,系统会把指定数组的内容推回到推回缓冲区,当推回输入流每次调用read方法时,总是先读取推回缓冲区的内容,只有推回缓冲区的内容读完之后,才会从原始流中读取。
例如: 找出程序中 "hello world" 字符串,找到后打印其前边的内容
public class PushbackInputStreamTest{
public static void main(String[] args){
try(
//指定推回缓冲区的长度为64
PushbackInputstream ps = new PushbackInputStream(new FileReader("text.txt"),64))
{
char[] buf = new char[32];
String lastContent = "";
int hasRead= 0;
while((hasRead = ps.read(buf)) >0){
String content = new String(buf,0,hasRead);
int index = 0;
if((index=(lastContent+content).indexOf("hello world"))>0){
ps.unread((lastContent+content).toCharArray()); // 将本次内容和上次的内容推回缓冲区
if(index > 32){
buf = new char[index];
}
ps.read(buf,0,index);
System.out.print(new String(buf,0,index));
System.exit(0);
} else {
System.out.print(lastContent);
lastContent = content;
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}