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 */
017package org.apache.commons.flatfile.util;
018
019import java.io.IOException;
020import java.io.InputStream;
021import java.util.Arrays;
022import java.util.Iterator;
023
024import org.apache.commons.lang3.Validate;
025
026/**
027 * Unified InputStream representation of multiple concatenated InputStreams.
028 * @version $Revision: 1301242 $ $Date: 2012-03-15 17:14:40 -0500 (Thu, 15 Mar 2012) $
029 */
030public class ConcatenatedInputStream extends InputStream {
031    /** EOF */
032    public static final int EOF = -1;
033
034    private static final InputStream AT_EOF = new InputStream() {
035        public int read() throws IOException {
036            return EOF;
037        }
038    };
039
040    private final Iterator<InputStream> iter;
041    private InputStream current;
042
043    /**
044     * Create a new ConcatenatedInputStream.
045     * @param src InputStreams
046     */
047    public ConcatenatedInputStream(Iterable<InputStream> src) {
048        this.iter = Validate.notNull(src).iterator();
049        next();
050    }
051
052    /**
053     * Create a new ConcatenatedInputStream.
054     * @param src InputStreams
055     */
056    public ConcatenatedInputStream(InputStream... src) {
057        this(Arrays.asList(Validate.notNull(src)));
058    }
059
060    /**
061     * {@inheritDoc}
062     */
063    public int read() throws IOException {
064        int n = current.read();
065        while (n == EOF && current != AT_EOF) {
066            next();
067            n = current.read();
068        }
069        return n;
070    }
071
072    /**
073     * Position to the next InputStream
074     */
075    private void next() {
076        current = iter.hasNext() ? iter.next() : AT_EOF;
077    }
078}