Explore Courses Blog Tutorials Interview Questions
0 votes
in Java by (3.9k points)
I am on the stage of development, where I have two modules and from one I got output as a OutputStream and second one, which accepts only InputStream. Do you know how to convert  OutputStream to InputStream (not vice versa, I mean really this way) that I will be able to connect these two parts?


1 Answer

0 votes
by (46k points)

As input and output streams are just roused and endpoint, the resolution is to temporarily save data in a byte array. So you must invest between ByteArrayOutputStream, from which you build a byte[] that is applied as input for new ByteArrayInputStream.

public void doTwoThingsWithStream(InputStream inStream, OutputStream outStream){ 

  //create temporary bayte array output stream

  ByteArrayOutputStream baos = new ByteArrayOutputStream();

  doFirstThing(inStream, baos);

  //create input stream from baos

  InputStream isFromFirstData = new ByteArrayInputStream(baos.toByteArray()); 

  doSecondThing(isFromFirstData, outStream);


I hope it helps.

Related questions

Browse Categories