O流中的PushbackReader 和PushbackInputStream这两个类的用法,有些疑惑?
import java.io.FileReader;
import java.io.IOException;
import java.io.PushbackReader;
public class PushbackTest {
public static void main(String[] args) throws IOException {
try(
PushbackReader pr = new PushbackReader(new FileReader("f:\\io\\a.txt"),64)) //这里应该是java7的自动关闭流动作
{
char[] buf = new char[32];
String lastContent = "";
int hasRead = 0;
while((hasRead = pr.read(buf)) != -1) //读取文件
{
//将读取内容转换字符串
String content = new String(buf,0,hasRead);
int targetIndex = 0;
if((targetIndex = (lastContent + content).indexOf("new PushbackReader")) !=-1 ) //如果包含“new pushbackReader”
{
pr.unread((lastContent + content).toCharArray());
int len = targetIndex > 32 ? 32 : targetIndex;
pr.read(buf,0,len);
System.out.println(new String(buf,0,len));
System.exit(0);
}else
{ //如果不包含
System.out.println(lastContent);
lastContent = content;
}
}
}
catch(IOException ioe){
ioe.printStackTrace();
}
}
}
|