1. /*
  2. * Copyright 2001-2004 The Apache Software Foundation.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. package org.apache.commons.io.output;
  17. import java.io.IOException;
  18. import java.io.OutputStream;
  19. /**
  20. * Data written to this stream is forwarded to a stream that has been associated
  21. * with this thread.
  22. *
  23. * @author <a href="mailto:peter@apache.org">Peter Donald</a>
  24. * @version $Revision: 1.5 $ $Date: 2004/02/23 04:40:29 $
  25. */
  26. public class DemuxOutputStream
  27. extends OutputStream
  28. {
  29. private InheritableThreadLocal m_streams = new InheritableThreadLocal();
  30. /**
  31. * Bind the specified stream to the current thread.
  32. *
  33. * @param output the stream to bind
  34. * @return the OutputStream that was previously active
  35. */
  36. public OutputStream bindStream( OutputStream output )
  37. {
  38. OutputStream stream = getStream();
  39. m_streams.set( output );
  40. return stream;
  41. }
  42. /**
  43. * Closes stream associated with current thread.
  44. *
  45. * @throws IOException if an error occurs
  46. */
  47. public void close()
  48. throws IOException
  49. {
  50. OutputStream output = getStream();
  51. if( null != output )
  52. {
  53. output.close();
  54. }
  55. }
  56. /**
  57. * Flushes stream associated with current thread.
  58. *
  59. * @throws IOException if an error occurs
  60. */
  61. public void flush()
  62. throws IOException
  63. {
  64. OutputStream output = getStream();
  65. if( null != output )
  66. {
  67. output.flush();
  68. }
  69. }
  70. /**
  71. * Writes byte to stream associated with current thread.
  72. *
  73. * @param ch the byte to write to stream
  74. * @throws IOException if an error occurs
  75. */
  76. public void write( int ch )
  77. throws IOException
  78. {
  79. OutputStream output = getStream();
  80. if( null != output )
  81. {
  82. output.write( ch );
  83. }
  84. }
  85. /**
  86. * Utility method to retrieve stream bound to current thread (if any).
  87. */
  88. private OutputStream getStream()
  89. {
  90. return (OutputStream)m_streams.get();
  91. }
  92. }