KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > commons > io > input > DemuxInputStream


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.input;
17
18 import java.io.IOException JavaDoc;
19 import java.io.InputStream JavaDoc;
20
21 /**
22  * Data written to this stream is forwarded to a stream that has been associated
23  * with this thread.
24  *
25  * @author <a HREF="mailto:peter@apache.org">Peter Donald</a>
26  * @version $Revision: 1.5 $ $Date: 2004/02/23 04:38:52 $
27  */

28 public class DemuxInputStream
29     extends InputStream JavaDoc
30 {
31     private InheritableThreadLocal JavaDoc m_streams = new InheritableThreadLocal JavaDoc();
32
33     /**
34      * Bind the specified stream to the current thread.
35      *
36      * @param input the stream to bind
37      * @return the InputStream that was previously active
38      */

39     public InputStream JavaDoc bindStream( InputStream JavaDoc input )
40     {
41         InputStream JavaDoc oldValue = getStream();
42         m_streams.set( input );
43         return oldValue;
44     }
45
46     /**
47      * Closes stream associated with current thread.
48      *
49      * @throws IOException if an error occurs
50      */

51     public void close()
52         throws IOException JavaDoc
53     {
54         InputStream JavaDoc input = getStream();
55         if( null != input )
56         {
57             input.close();
58         }
59     }
60
61     /**
62      * Read byte from stream associated with current thread.
63      *
64      * @return the byte read from stream
65      * @throws IOException if an error occurs
66      */

67     public int read()
68         throws IOException JavaDoc
69     {
70         InputStream JavaDoc input = getStream();
71         if( null != input )
72         {
73             return input.read();
74         }
75         else
76         {
77             return -1;
78         }
79     }
80
81     /**
82      * Utility method to retrieve stream bound to current thread (if any).
83      */

84     private InputStream JavaDoc getStream()
85     {
86         return (InputStream JavaDoc)m_streams.get();
87     }
88 }
89
Popular Tags