1/*
2 * Copyright (C) 2008 The Guava Authors
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
17package com.google.common.io;
18
19import com.google.common.base.Preconditions;
20
21import java.io.IOException;
22import java.io.Reader;
23import java.util.Iterator;
24
25/**
26 * A {@link Reader} that concatenates multiple readers.
27 *
28 * @author Bin Zhu
29 * @since 1.0
30 */
31class MultiReader extends Reader {
32  private final Iterator<? extends InputSupplier<? extends Reader>> it;
33  private Reader current;
34
35  MultiReader(Iterator<? extends InputSupplier<? extends Reader>> readers)
36      throws IOException {
37    this.it = readers;
38    advance();
39  }
40
41  /**
42   * Closes the current reader and opens the next one, if any.
43   */
44  private void advance() throws IOException {
45    close();
46    if (it.hasNext()) {
47      current = it.next().getInput();
48    }
49  }
50
51  @Override public int read(char cbuf[], int off, int len) throws IOException {
52    if (current == null) {
53      return -1;
54    }
55    int result = current.read(cbuf, off, len);
56    if (result == -1) {
57      advance();
58      return read(cbuf, off, len);
59    }
60    return result;
61  }
62
63  @Override public long skip(long n) throws IOException {
64    Preconditions.checkArgument(n >= 0, "n is negative");
65    if (n > 0) {
66      while (current != null) {
67        long result = current.skip(n);
68        if (result > 0) {
69          return result;
70        }
71        advance();
72      }
73    }
74    return 0;
75  }
76
77  @Override public boolean ready() throws IOException {
78    return (current != null) && current.ready();
79  }
80
81  @Override public void close() throws IOException {
82    if (current != null) {
83      try {
84        current.close();
85      } finally {
86        current = null;
87      }
88    }
89  }
90}
91