View Javadoc
1   /*
2    * Copyright (C) 2008 The Guava Authors
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
5    * in compliance with the License. You may obtain a copy of the License at
6    *
7    * http://www.apache.org/licenses/LICENSE-2.0
8    *
9    * Unless required by applicable law or agreed to in writing, software distributed under the License
10   * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
11   * or implied. See the License for the specific language governing permissions and limitations under
12   * the License.
13   */
14  
15  package com.google.common.io;
16  
17  import com.google.common.annotations.GwtIncompatible;
18  import com.google.common.base.Preconditions;
19  import java.io.IOException;
20  import java.io.Reader;
21  import java.util.Iterator;
22  import javax.annotation.Nullable;
23  
24  /**
25   * A {@link Reader} that concatenates multiple readers.
26   *
27   * @author Bin Zhu
28   * @since 1.0
29   */
30  @GwtIncompatible
31  class MultiReader extends Reader {
32    private final Iterator<? extends CharSource> it;
33    private Reader current;
34  
35    MultiReader(Iterator<? extends CharSource> readers) throws IOException {
36      this.it = readers;
37      advance();
38    }
39  
40    /**
41     * Closes the current reader and opens the next one, if any.
42     */
43    private void advance() throws IOException {
44      close();
45      if (it.hasNext()) {
46        current = it.next().openStream();
47      }
48    }
49  
50    @Override
51    public int read(@Nullable 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
64    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
79    public boolean ready() throws IOException {
80      return (current != null) && current.ready();
81    }
82  
83    @Override
84    public void close() throws IOException {
85      if (current != null) {
86        try {
87          current.close();
88        } finally {
89          current = null;
90        }
91      }
92    }
93  }