Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add bytes to InputStream

I would like to simulate a behaviour in a unit test of an InputStream that (as InputStreams do) blocks until further data is available. That requires me to append bytes to the InputStream in chunks so that the consumer reads them in chunks, too. Something like this:

@Test
public void readAllInput() throws Exception {
    ???InputStream in = ...; // ???
    Consumer consumer = new Consumer(in);
    Thread consumingThread = new Thread(consumer).start();

    in.add("one".getBytes("UTF-8")); // ???
    in.add("two".getBytes("UTF-8")); // ???
    in.close();
    consumingThread.join();

    assertThat(consumer.getDataAsString()).isEqualTo("onetwo");
}

class Consumer implements Runnable {
    private InputStream in;
    private ByteArrayOutputStream out = new ByteArrayOutputStream();

    public Consumer(InputStream in) {
        this.in = in;
    }

    public void run() {
        IOUtils.copy(in, out);
    }

    public String getDataAsString() {
        return out.toString("UTF-8");
    }
}

What kind of InputStream (or any other solution) would allow me to append the data on one end and consume them from the other?

Note: The Consumer needs to have InputStream-based API (not Reader).

like image 304
Adam Michalik Avatar asked Apr 15 '26 13:04

Adam Michalik


1 Answers

As you're using threads, this is a rare case for a pair of PipedInputStream/PipedOutputStream.

like image 66
user207421 Avatar answered Apr 18 '26 03:04

user207421



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!