Note that there are some explanatory texts on larger screens.

plurals
  1. POJava - A Reader class able to interleave lines from multiple Readers
    primarykey
    data
    text
    <p>What I would like is to end up with something like:</p> <pre><code>public class InterleavedBufferedReader extends BufferedReader { ... } </code></pre> <p>And use it as:</p> <pre><code>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 </code></pre> <p>What I tried (no good, I know, that's why I'm here):</p> <pre><code>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 &lt; 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 &lt; buffers.length; i++) buffers[i].close(); } } </code></pre> <p>Comments:</p> <ul> <li>The interleaved <code>readLine()</code> actually works!</li> <li>Perhaps I shouldn't be extending <code>BufferedReader</code>. I'm forced to give it a dummy Reader to manage, or it won't even compile. Meanwhile, I override the <code>readLine()</code> method to call it on the children readers. But the implementation is at least incomplete, because other methods, as <code>read()</code>, will actually refer to my dummy reader. </li> </ul> <p>I can I do this in a cleaner way?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload