Duško Mirković
Duško Mirković

Reputation: 321

Write from one OutputStream to another InputStream

I want to have an InputStream in a class like this:

class A {

    InputStream inputStream = ...

}

And I want to write to that InputStream using a OutputStream from another class which is in the same application. Is it possible to do this?

Upvotes: 0

Views: 331

Answers (1)

sb27
sb27

Reputation: 392

Yes it is! PipedOutputStream (see) and a PipedInputStream (see) is what you need.

Here is a little example how to use it:

public static void main(String[] args) throws ParseException, IOException {
    PipedInputStream inputStream = new PipedInputStream();
    PipedOutputStream outputStream = new PipedOutputStream(inputStream);

    // Write some data to the output stream
    writeDataToOutputStream(outputStream);

    // Now read that data
    Scanner src = new Scanner(inputStream);

    System.out.println(src.nextLine());
}

private static void writeDataToOutputStream(OutputStream outputStream) throws IOException {
    outputStream.write("Hello!\n".getBytes());
}

The code will output:

Hello!

Upvotes: 1

Related Questions