PushbackInputStream和PushbackReader是推回输入流,它们有一片推回缓冲区域,在读取数据时,会优先从推回缓冲区域读取,只有推回缓冲区域的内容没有装满read()所需数组的大小时才会去流中读取。
public class PushbackTest {
public static void main(String[] args) {
// 指定推回缓冲区长度为64.
try (PushbackReader pr = new PushbackReader(new FileReader(
"src/inputandoutput/PushbackTest.java"), 64)) {
char[] buff = new char[32];
String lastContent = "";
int hasRead = 0;
while ((hasRead = pr.read(buff)) > 0) {
String content = new String(buff, 0, hasRead);
int targetIndex = 0;
if ((targetIndex = (content + lastContent)
.indexOf("new PushbackIndex")) > 0) {
pr.unread((lastContent + content).toCharArray());
if (targetIndex > 32) {
buff = new char[targetIndex];
}
pr.read(buff, 0, targetIndex);
System.out.print(new String(buff, 0, targetIndex));
System.exit(0);
} else {
System.out.println(lastContent);
lastContent = content;
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
京公网安备 11010502036488号