View Javadoc

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.flatfile.util;
18  
19  import java.io.IOException;
20  import java.io.InputStream;
21  import java.util.Arrays;
22  import java.util.Iterator;
23  
24  import org.apache.commons.lang3.Validate;
25  
26  /**
27   * Unified InputStream representation of multiple concatenated InputStreams.
28   * @version $Revision: 1301242 $ $Date: 2012-03-15 17:14:40 -0500 (Thu, 15 Mar 2012) $
29   */
30  public class ConcatenatedInputStream extends InputStream {
31      /** EOF */
32      public static final int EOF = -1;
33  
34      private static final InputStream AT_EOF = new InputStream() {
35          public int read() throws IOException {
36              return EOF;
37          }
38      };
39  
40      private final Iterator<InputStream> iter;
41      private InputStream current;
42  
43      /**
44       * Create a new ConcatenatedInputStream.
45       * @param src InputStreams
46       */
47      public ConcatenatedInputStream(Iterable<InputStream> src) {
48          this.iter = Validate.notNull(src).iterator();
49          next();
50      }
51  
52      /**
53       * Create a new ConcatenatedInputStream.
54       * @param src InputStreams
55       */
56      public ConcatenatedInputStream(InputStream... src) {
57          this(Arrays.asList(Validate.notNull(src)));
58      }
59  
60      /**
61       * {@inheritDoc}
62       */
63      public int read() throws IOException {
64          int n = current.read();
65          while (n == EOF && current != AT_EOF) {
66              next();
67              n = current.read();
68          }
69          return n;
70      }
71  
72      /**
73       * Position to the next InputStream
74       */
75      private void next() {
76          current = iter.hasNext() ? iter.next() : AT_EOF;
77      }
78  }