我想要的结果是:
public class InterleavedBufferedReader extends BufferedReader {
...
}
并将其用作:
Reader[3] readers = ...; // three readers
InterleavedBufferedReader ibr = new InterleavedBufferedReader(readers);
ibr.readLine(); // this returns the first line of Reader 1
ibr.readLine(); // this returns the first line of Reader 2
ibr.readLine(); // this returns the first line of Reader 3
ibr.readLine(); // this returns the second line of Reader 1
ibr.readLine(); // this returns the second line of Reader 2
ibr.readLine(); // hey, Reader 3 had no more lines, return the third line of Reader 1
我尝试了什么(不好,我知道,这就是我在这里的原因):
public class InterleavedBufferedReader extends BufferedReader {
static private int current = 0;
private BufferedReader[] buffers;
public InterleavedBufferedReader(BufferedReader[] in) {
super(new StringReader("dummy"));
buffers = in;
}
public InterleavedBufferedReader(Reader[] in) {
super(new StringReader("dummy"));
buffers = new BufferedReader[in.length];
for (int i=0 ; i < in.length ; i++)
buffers[i] = new BufferedReader(in[i]);
}
@Override
public String readLine() throws IOException {
int start = current;
String line = null;
while ((line = buffers[current].readLine()) == null) {
current = (current+1) % buffers.length;
if (current == start)
return null;
}
current = (current+1) % buffers.length;
return line;
}
@Override
public void close() throws IOException {
for (int i=0; i < buffers.length; i++)
buffers[i].close();
}
}
注释:
- 交错
readLine()
确实有效! - 也许我不应该延长
BufferedReader
。我不得不给它一个虚拟的 Reader 来管理,否则它甚至不会编译。同时,我重写了readLine()
在儿童阅读器上调用它的方法。但是实现至少是不完整的,因为其他方法,如read()
,实际上将引用我的虚拟读者。
我可以以更清洁的方式做到这一点吗?