推回输入流就是讲字节或字符数组内容推回到推回缓冲区里面,从而允许重复读取刚刚读取的内容
当程序创建一个推回输入流时需要指定推回缓冲区的大小,默认的推回缓冲区长度为一,如果程序推回到推回缓冲区的内容超出了推回缓冲区的大小,将会引发Pushback buffer overflow 异常。
下面看例子
package IOTest; import java.io.FileReader; import java.io.IOException; import java.io.PushbackInputStream; import java.io.PushbackReader; public class PushbackTest { public static void main(String[] args){ try( PushbackReader pushbackReader = new PushbackReader(new FileReader("./src/main/java/IOTest/Push" + "backTest.java"),64) ) { char[] buf = new char[32]; String lastContent = ""; int hasRead = 0; while ((hasRead = pushbackReader.read(buf))>0) { String content = new String(buf,0,hasRead); int targetIndex = 0; if((targetIndex = (lastContent + content).indexOf("new PushbackReader"))>0){ pushbackReader.unread((lastContent+content).toCharArray()); if(targetIndex > 32) { buf = new char[targetIndex]; } pushbackReader.read(buf,0,targetIndex); System.out.println(new String(buf,0,targetIndex)); System.exit(0); } else{ System.out.println(lastContent); lastContent = content; } } }catch (IOException ex){ ex.printStackTrace(); } } }
输出
推回输入流在进行输入时先从推回缓冲区读取,当推回缓冲区中的数据读取完了之后才从输入流中读取数据。