001 /* 002 * Licensed to the Apache Software Foundation (ASF) under one or more 003 * contributor license agreements. See the NOTICE file distributed with 004 * this work for additional information regarding copyright ownership. 005 * The ASF licenses this file to You under the Apache License, Version 2.0 006 * (the "License"); you may not use this file except in compliance with 007 * the License. You may obtain a copy of the License at 008 * 009 * http://www.apache.org/licenses/LICENSE-2.0 010 * 011 * Unless required by applicable law or agreed to in writing, software 012 * distributed under the License is distributed on an "AS IS" BASIS, 013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 014 * See the License for the specific language governing permissions and 015 * limitations under the License. 016 */ 017 package org.apache.commons.io.output; 018 019 import java.io.IOException; 020 import java.io.OutputStream; 021 022 /** 023 * Data written to this stream is forwarded to a stream that has been associated 024 * with this thread. 025 * 026 * @author <a href="mailto:peter@apache.org">Peter Donald</a> 027 * @version $Revision: 437567 $ $Date: 2006-08-28 07:39:07 +0100 (Mon, 28 Aug 2006) $ 028 */ 029 public class DemuxOutputStream 030 extends OutputStream 031 { 032 private InheritableThreadLocal m_streams = new InheritableThreadLocal(); 033 034 /** 035 * Bind the specified stream to the current thread. 036 * 037 * @param output the stream to bind 038 * @return the OutputStream that was previously active 039 */ 040 public OutputStream bindStream( OutputStream output ) 041 { 042 OutputStream stream = getStream(); 043 m_streams.set( output ); 044 return stream; 045 } 046 047 /** 048 * Closes stream associated with current thread. 049 * 050 * @throws IOException if an error occurs 051 */ 052 public void close() 053 throws IOException 054 { 055 OutputStream output = getStream(); 056 if( null != output ) 057 { 058 output.close(); 059 } 060 } 061 062 /** 063 * Flushes stream associated with current thread. 064 * 065 * @throws IOException if an error occurs 066 */ 067 public void flush() 068 throws IOException 069 { 070 OutputStream output = getStream(); 071 if( null != output ) 072 { 073 output.flush(); 074 } 075 } 076 077 /** 078 * Writes byte to stream associated with current thread. 079 * 080 * @param ch the byte to write to stream 081 * @throws IOException if an error occurs 082 */ 083 public void write( int ch ) 084 throws IOException 085 { 086 OutputStream output = getStream(); 087 if( null != output ) 088 { 089 output.write( ch ); 090 } 091 } 092 093 /** 094 * Utility method to retrieve stream bound to current thread (if any). 095 * 096 * @return the output stream 097 */ 098 private OutputStream getStream() 099 { 100 return (OutputStream)m_streams.get(); 101 } 102 }