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?

2
  • Take a Look at PipedInputStream and PipedOutputStream Commented Oct 22, 2020 at 19:06
  • THere's an answer here that looks relevant: stackoverflow.com/questions/43157/… Commented Oct 22, 2020 at 19:06

1 Answer 1

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!
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.