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