0

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?

  • Take a Look at PipedInputStream and PipedOutputStream – Felix Oct 22 '20 at 19:06
  • THere's an answer here that looks relevant: https://stackoverflow.com/questions/43157/easy-way-to-write-contents-of-a-java-inputstream-to-an-outputstream – Gus Oct 22 '20 at 19:06

1 Answers1

1

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!
sb27
  • 382
  • 4
  • 14