Java中的PushbackReader流理解

按照注释,unread()会将内容推回到推回缓冲区,这段代码的关键是看每次读取的字符数组的大小,这边定位为32,如果小于一个值的话,是会全部打印出来的,因为每次读取的
内容的长度要足够长,才能在一次读取中完整的读取“new PushbackReader”这个字符串。
package sun;


import java.io.*;
/**
 * Description:
 * 
Copyright (C), 2005-2008, Yeeku.H.Lee *
This program is protected by copyright laws. *
Program Name: *
Date: * @author Yeeku.H.Lee [email protected] * @version 1.0 */ public class Test { public static void main(String[] args) { PushbackReader pr = null; try { //创建一个PushbackReader对象,指定推回缓冲区的长度为64 pr = 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(); } } } }


你可能感兴趣的:(Java)