Java中的PushbackReader流理解

来源:互联网 发布:人工智能百度云资源 编辑:程序博客网 时间:2024/05/29 15:43
按照注释,unread()会将内容推回到推回缓冲区,这段代码的关键是看每次读取的字符数组的大小,这边定位为32,如果小于一个值的话,是会全部打印出来的,因为每次读取的
内容的长度要足够长,才能在一次读取中完整的读取“new PushbackReader”这个字符串。
package sun;import java.io.*;/** * Description: * <br/>Copyright (C), 2005-2008, Yeeku.H.Lee * <br/>This program is protected by copyright laws. * <br/>Program Name: * <br/>Date: * @author  Yeeku.H.Lee kongyeeku@163.com * @version  1.0 */public class Test{public static void main(String[] args) {PushbackReader pr = null;try{//创建一个PushbackReader对象,指定推回缓冲区的长度为64pr = new PushbackReader(new FileReader("/Users/AllSun/Desktop/疯狂java讲义源代码/codes/codes/15/15-4/PushbackTest.java") , 64);char[] buf = new char[32];//用以保存上次读取的字符串内容String lastContent = "";int hasRead = 0;//循环读取文件内容while ((hasRead = pr.read(buf)) > 0){//将读取的内容转换成字符串String content = new String(buf , 0 , hasRead);int targetIndex = 0;//将上次读取的字符串和本次读取的字符串拼起来,查看是否包含目标字符串//如果包含目标字符串if ((targetIndex = (lastContent + content).indexOf("new PushbackReader")) > 0){//将本次内容和上次内容一起推回缓冲区pr.unread((lastContent + content).toCharArray());//再次读取指定长度的内容(就是目标字符串之前的内容)pr.read(buf , 0 , targetIndex);//打印读取的内容System.out.print(new String(buf , 0 ,targetIndex));int i = 0;System.out.println(++i);System.exit(0);}else{//打印上次读取的内容System.out.print(lastContent);//将本次内容设为上次读取的内容lastContent = content;}}}catch (IOException ioe){ioe.printStackTrace();}finally{try{if (pr != null)pr.close();}catch (IOException ioe){ioe.printStackTrace();}}}}


0 0
原创粉丝点击