没有办法开箱即用。你可以写一个装饰器来做这件事,也许有一堆标记。但是,如果您只关心逐行阅读和倒带,我认为更简单的实现是使用列表来维护“历史”和“回退”。
我认为描述它会比 Teh Codez 花费更多的行数,所以这是实现的第一步(这不是生产质量代码;一方面,它不限制历史列表,所以你很容易用完内存):
import java.io.BufferedReader;
import java.io.IOException;
import java.util.LinkedList;
public class ReaderBuffer
{
private BufferedReader reader;
private LinkedList<String> history = new LinkedList<String>();
private LinkedList<String> future = new LinkedList<String>();
public ReaderBuffer(BufferedReader reader)
{
this.reader = reader;
}
public String readLine()
throws IOException
{
String line = null;
if (future.size() > 0)
line = future.removeFirst();
if (line == null)
line = reader.readLine();
if (line != null)
history.add(line);
return line;
}
public void rewind(int numLines)
{
for (int ii = 0 ; ii < numLines ; ii++)
future.addFirst(history.removeLast());
}
}
这是一个如何使用它的例子:
@Test
public void testRewind() throws Exception
{
BufferedReader rdr = new BufferedReader(new StringReader("foo\nbar\nbaz\n"));
ReaderBuffer buf = new ReaderBuffer(rdr);
assertEquals("foo", buf.readLine());
assertEquals("bar", buf.readLine());
assertEquals("baz", buf.readLine());
assertEquals(null, buf.readLine());
buf.rewind(2);
assertEquals("bar", buf.readLine());
assertEquals("baz", buf.readLine());
assertEquals(null, buf.readLine());
}