View Javadoc

1   /*
2    * $Id: ChainedReader.java 19191 2010-08-25 21:05:23Z tcarlson $
3    * --------------------------------------------------------------------------------------
4    * Copyright (c) MuleSoft, Inc.  All rights reserved.  http://www.mulesoft.com
5    *
6    * The software in this package is published under the terms of the CPAL v1.0
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;
14  import java.io.Reader;
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
21  {
22      private final Reader first;
23      private final Reader second;
24      private boolean firstRead = false;
25  
26      public ChainedReader(Reader first, Reader second)
27      {
28          this.first = first;
29          this.second = second;
30      }
31  
32      public void close() throws IOException
33      {
34          first.close();
35          second.close();
36      }
37  
38      public int read(char[] cbuf, int off, int len) throws IOException
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
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
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 }