KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > mule > util > ChainedReader


1 /*
2  * $Id: ChainedReader.java 3196 2006-09-24 22:50:50Z holger $
3  * --------------------------------------------------------------------------------------
4  * Copyright (c) MuleSource, Inc. All rights reserved. http://www.mulesource.com
5  *
6  * The software in this package is published under the terms of the MuleSource MPL
7  * license, a copy of which has been included with this distribution in the
8  * LICENSE.txt file.
9  */

10
11 package org.mule.util;
12
13 import java.io.IOException JavaDoc;
14 import java.io.Reader JavaDoc;
15
16 /**
17  * <code>ChainedReader</code> allows Reader objects to be chained together. Useful
18  * for concatenating data from multiple Reader objects.
19  */

20 public class ChainedReader extends Reader JavaDoc
21 {
22     private final Reader JavaDoc first;
23     private final Reader JavaDoc second;
24     private boolean firstRead = false;
25
26     public ChainedReader(Reader JavaDoc first, Reader JavaDoc second)
27     {
28         this.first = first;
29         this.second = second;
30     }
31
32     public void close() throws IOException JavaDoc
33     {
34         first.close();
35         second.close();
36     }
37
38     public int read(char[] cbuf, int off, int len) throws IOException JavaDoc
39     {
40         if (!firstRead)
41         {
42             int i = first.read(cbuf, off, len);
43             if (i < len)
44             {
45                 firstRead = true;
46                 int x = second.read(cbuf, i, len - i);
47                 return x + i;
48             }
49             else
50             {
51                 return i;
52             }
53         }
54         else
55         {
56             return second.read(cbuf, off, len);
57         }
58     }
59
60     public int read() throws IOException JavaDoc
61     {
62         if (!firstRead)
63         {
64             int i = first.read();
65             if (i == -1)
66             {
67                 firstRead = true;
68                 return second.read();
69             }
70             else
71             {
72                 return i;
73             }
74         }
75         else
76         {
77             return second.read();
78         }
79     }
80
81     public int read(char[] cbuf) throws IOException JavaDoc
82     {
83         if (!firstRead)
84         {
85             int i = first.read(cbuf);
86             if (i < cbuf.length)
87             {
88                 firstRead = true;
89                 int x = second.read(cbuf, i, cbuf.length - i);
90                 return x + i;
91             }
92             else
93             {
94                 return i;
95             }
96         }
97         else
98         {
99             return second.read(cbuf);
100         }
101     }
102
103 }
104
Popular Tags