gpt4 book ai didi

Java - 一个 Reader 类,能够交错来自多个 Reader 的行

转载 作者:行者123 更新时间:2023-12-04 05:36:05 26 4
gpt4 key购买 nike

我想要的是最终得到类似的东西:

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()方法在 child 读者上调用它。但至少实现是不完整的,因为其他方法,如read() ,实际上是指我的虚拟读者。

  • 我可以以更清洁的方式做到这一点吗?

    最佳答案

    Perhaps I shouldn't be extending BufferedReader. I'm forced to give it a dummy Reader to manage, or it won't even compile. [...] the implementation is at least incomplete, because other methods, as read(), will actually refer to my dummy reader



    您可以而且应该覆盖 read() (和 ready() )也是如此。 readLine() 的实现必须保留,但至少您确定所有阅读方法都符合您希望实现的交错。虚拟阅读器无法避免,但您的实现可以。您甚至可能希望将 BufferedReader 的缓冲区设置为您可以使用的最低值 (1),以减少内存浪费。

    除此之外,您不能忘记流的标记支持:您必须通过覆盖 mark() 重新实现它。和 reset() ,或者只是覆盖 markSupported()所以它总是返回false。

    关于Java - 一个 Reader 类,能够交错来自多个 Reader 的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11915254/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com