0

I have two object:

BufferedReader br;
CMSSignedData cms;

I have to write cms content to BufferedReader cms has this method:

 cms.getSignedContent().write(OutputStream os); 

But how to get the OutputStream from BufferedReader?

This is my attemp:

        ByteArrayOutputStream os=new ByteArrayOutputStream();
        cms.getSignedContent().write(os);
        InputStream is=new ByteArrayInputStream(os.toByteArray());  
        BufferedReader br = new BufferedReader(new InputStreamReader(is));

But I don't think this is the best way.

Tobia
  • 9,165
  • 28
  • 114
  • 219

1 Answers1

1

I think what you want is a piped input/output stream.

PipedOutputStream os = new PipedOutputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(new PipedInputStream(os)));
cms.getSignedContent().write(os);

Take note of piet.t's comment on threads however.

As well as check the relevant APIs docs:

thSoft
  • 21,755
  • 5
  • 88
  • 103
Mex
  • 508
  • 4
  • 15
  • I don't see how your output and input are connected in this example. – Duncan Jones Dec 05 '13 at 12:13
  • This would have been my suggestion too. But keep in mind that `PipedInputStream` and `PipedOutputStream` should live in different threads to avoid deadlocks. But any clean solution either has to make use of some explicit buffer-space or two threads (one for reading, one for writing). – piet.t Dec 05 '13 at 12:13
  • @Duncan there was a typo in code, corrected it. – piet.t Dec 05 '13 at 12:14
  • I don't want to use two thread. May I use Piped? Why do you think this is better than a raw ByteArray? Thanks – Tobia Dec 05 '13 at 13:40
  • This post has an nice asnwer that makes the threading simple. http://stackoverflow.com/questions/1225909/most-efficient-way-to-create-inputstream-from-outputstream – Mex Dec 05 '13 at 15:49
  • 2
    @Tobia When using the byte-array you dump all data to be transfered into the heap while using PipedStreams data can be passed from Stream to Stream byte by byte, at the speed it is generated or consumed. That might not be worth the trouble for small data, but think of Streams of hundreds of Megabytes... – piet.t Dec 05 '13 at 15:58