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