Posted By

dvdsmnt on 11/14/09


Tagged

java io pipe stream PipedInputStream


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

dvdsmnt


Convert OutputSream into an InputStream


 / Published in: Java
 

URL: http://code.google.com/p/io-tools/wiki/Tutorial_EasyStream

There are many ways to retrieve data written to an OutputStream in an InputStream class. An introduction can be found at io-tools website :

InputStreamFromOutputStream

This is the hardest way, but it offers some advantages:

  • This class internally use pipes, so it has a fixed memory fingerprint (doesn't fill up your memory with data).
  • Details of threads are hidden from the user. You don't have to deal with instantiation/start/synchronization/stop.
  • You can easily choose between many options for instantiating new Threads (thread pool, thread per instance ...) or just don't care and get the default.
  • Details of pipes are hidden. No PipeInputStream or PipeOutputStream in your code.
  • The internal pipe size can be adjusted to fit your needs.
  1. final String dataId=//id of some data.
  2. final InputStreamFromOutputStream<String> isos = new InputStreamFromOutputStream<String>() {
  3. @Override
  4. public String produce(final OutputStream dataSink) throws Exception {
  5. /*
  6.   * call your application function who produces the data here
  7.   * WARNING: we're in another thread here, so this method shouldn't
  8.   * write any class field or make assumptions on the state of the class.
  9.   */
  10. return produceMydata(dataId,dataSink)
  11. }
  12. };
  13. try {
  14. //now you can read from the InputStream the data that was written to the
  15. //dataSink OutputStream
  16. byte[] readed=IOUtils.toByteArray(isos);
  17. //Use data here
  18. } catch (final IOException e) {
  19. //Handle exception here
  20. } finally {
  21. isos.close();
  22. }
  23. //You can get the result of produceMyData after the stream has been closed.
  24. String resultOfProduction = isos.getResult();
  25. }

Report this snippet  

You need to login to post a comment.