001/* 002 * Copyright (C) 2012 The Guava Authors 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except 005 * in compliance with the License. You may obtain a copy of the License at 006 * 007 * http://www.apache.org/licenses/LICENSE-2.0 008 * 009 * Unless required by applicable law or agreed to in writing, software distributed under the License 010 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 011 * or implied. See the License for the specific language governing permissions and limitations under 012 * the License. 013 */ 014 015package com.google.common.io; 016 017import static com.google.common.base.Preconditions.checkNotNull; 018import static com.google.common.collect.Streams.stream; 019 020import com.google.common.annotations.GwtIncompatible; 021import com.google.common.annotations.J2ktIncompatible; 022import com.google.common.base.Ascii; 023import com.google.common.base.Optional; 024import com.google.common.base.Splitter; 025import com.google.common.collect.AbstractIterator; 026import com.google.common.collect.ImmutableList; 027import com.google.common.collect.Lists; 028import com.google.errorprone.annotations.CanIgnoreReturnValue; 029import com.google.errorprone.annotations.MustBeClosed; 030import java.io.BufferedReader; 031import java.io.Closeable; 032import java.io.IOException; 033import java.io.InputStream; 034import java.io.Reader; 035import java.io.StringReader; 036import java.io.UncheckedIOException; 037import java.io.Writer; 038import java.nio.charset.Charset; 039import java.util.Iterator; 040import java.util.List; 041import java.util.function.Consumer; 042import java.util.stream.Stream; 043import javax.annotation.CheckForNull; 044import org.checkerframework.checker.nullness.qual.Nullable; 045 046/** 047 * A readable source of characters, such as a text file. Unlike a {@link Reader}, a {@code 048 * CharSource} is not an open, stateful stream of characters that can be read and closed. Instead, 049 * it is an immutable <i>supplier</i> of {@code Reader} instances. 050 * 051 * <p>{@code CharSource} provides two kinds of methods: 052 * 053 * <ul> 054 * <li><b>Methods that return a reader:</b> These methods should return a <i>new</i>, independent 055 * instance each time they are called. The caller is responsible for ensuring that the 056 * returned reader is closed. 057 * <li><b>Convenience methods:</b> These are implementations of common operations that are 058 * typically implemented by opening a reader using one of the methods in the first category, 059 * doing something and finally closing the reader that was opened. 060 * </ul> 061 * 062 * <p>Several methods in this class, such as {@link #readLines()}, break the contents of the source 063 * into lines. Like {@link BufferedReader}, these methods break lines on any of {@code \n}, {@code 064 * \r} or {@code \r\n}, do not include the line separator in each line and do not consider there to 065 * be an empty line at the end if the contents are terminated with a line separator. 066 * 067 * <p>Any {@link ByteSource} containing text encoded with a specific {@linkplain Charset character 068 * encoding} may be viewed as a {@code CharSource} using {@link ByteSource#asCharSource(Charset)}. 069 * 070 * <p><b>Note:</b> In general, {@code CharSource} is intended to be used for "file-like" sources 071 * that provide readers that are: 072 * 073 * <ul> 074 * <li><b>Finite:</b> Many operations, such as {@link #length()} and {@link #read()}, will either 075 * block indefinitely or fail if the source creates an infinite reader. 076 * <li><b>Non-destructive:</b> A <i>destructive</i> reader will consume or otherwise alter the 077 * source as they are read from it. A source that provides such readers will not be reusable, 078 * and operations that read from the stream (including {@link #length()}, in some 079 * implementations) will prevent further operations from completing as expected. 080 * </ul> 081 * 082 * @since 14.0 083 * @author Colin Decker 084 */ 085@J2ktIncompatible 086@GwtIncompatible 087@ElementTypesAreNonnullByDefault 088public abstract class CharSource { 089 090 /** Constructor for use by subclasses. */ 091 protected CharSource() {} 092 093 /** 094 * Returns a {@link ByteSource} view of this char source that encodes chars read from this source 095 * as bytes using the given {@link Charset}. 096 * 097 * <p>If {@link ByteSource#asCharSource} is called on the returned source with the same charset, 098 * the default implementation of this method will ensure that the original {@code CharSource} is 099 * returned, rather than round-trip encoding. Subclasses that override this method should behave 100 * the same way. 101 * 102 * @since 20.0 103 */ 104 public ByteSource asByteSource(Charset charset) { 105 return new AsByteSource(charset); 106 } 107 108 /** 109 * Opens a new {@link Reader} for reading from this source. This method returns a new, independent 110 * reader each time it is called. 111 * 112 * <p>The caller is responsible for ensuring that the returned reader is closed. 113 * 114 * @throws IOException if an I/O error occurs while opening the reader 115 */ 116 public abstract Reader openStream() throws IOException; 117 118 /** 119 * Opens a new {@link BufferedReader} for reading from this source. This method returns a new, 120 * independent reader each time it is called. 121 * 122 * <p>The caller is responsible for ensuring that the returned reader is closed. 123 * 124 * @throws IOException if an I/O error occurs while of opening the reader 125 */ 126 public BufferedReader openBufferedStream() throws IOException { 127 Reader reader = openStream(); 128 return (reader instanceof BufferedReader) 129 ? (BufferedReader) reader 130 : new BufferedReader(reader); 131 } 132 133 /** 134 * Opens a new {@link Stream} for reading text one line at a time from this source. This method 135 * returns a new, independent stream each time it is called. 136 * 137 * <p>The returned stream is lazy and only reads from the source in the terminal operation. If an 138 * I/O error occurs while the stream is reading from the source or when the stream is closed, an 139 * {@link UncheckedIOException} is thrown. 140 * 141 * <p>Like {@link BufferedReader#readLine()}, this method considers a line to be a sequence of 142 * text that is terminated by (but does not include) one of {@code \r\n}, {@code \r} or {@code 143 * \n}. If the source's content does not end in a line termination sequence, it is treated as if 144 * it does. 145 * 146 * <p>The caller is responsible for ensuring that the returned stream is closed. For example: 147 * 148 * <pre>{@code 149 * try (Stream<String> lines = source.lines()) { 150 * lines.map(...) 151 * .filter(...) 152 * .forEach(...); 153 * } 154 * }</pre> 155 * 156 * @throws IOException if an I/O error occurs while opening the stream 157 * @since 22.0 (but only since 33.4.0 in the Android flavor) 158 */ 159 @MustBeClosed 160 public Stream<String> lines() throws IOException { 161 BufferedReader reader = openBufferedStream(); 162 return reader.lines().onClose(() -> closeUnchecked(reader)); 163 } 164 165 @SuppressWarnings("Java7ApiChecker") 166 @IgnoreJRERequirement // helper for lines() 167 /* 168 * If we make these calls inline inside the lambda inside lines(), we get an Animal Sniffer error, 169 * despite the @IgnoreJRERequirement annotation there. For details, see ImmutableSortedMultiset. 170 */ 171 private static void closeUnchecked(Closeable closeable) { 172 try { 173 closeable.close(); 174 } catch (IOException e) { 175 throw new UncheckedIOException(e); 176 } 177 } 178 179 /** 180 * Returns the size of this source in chars, if the size can be easily determined without actually 181 * opening the data stream. 182 * 183 * <p>The default implementation returns {@link Optional#absent}. Some sources, such as a {@code 184 * CharSequence}, may return a non-absent value. Note that in such cases, it is <i>possible</i> 185 * that this method will return a different number of chars than would be returned by reading all 186 * of the chars. 187 * 188 * <p>Additionally, for mutable sources such as {@code StringBuilder}s, a subsequent read may 189 * return a different number of chars if the contents are changed. 190 * 191 * @since 19.0 192 */ 193 public Optional<Long> lengthIfKnown() { 194 return Optional.absent(); 195 } 196 197 /** 198 * Returns the length of this source in chars, even if doing so requires opening and traversing an 199 * entire stream. To avoid a potentially expensive operation, see {@link #lengthIfKnown}. 200 * 201 * <p>The default implementation calls {@link #lengthIfKnown} and returns the value if present. If 202 * absent, it will fall back to a heavyweight operation that will open a stream, {@link 203 * Reader#skip(long) skip} to the end of the stream, and return the total number of chars that 204 * were skipped. 205 * 206 * <p>Note that for sources that implement {@link #lengthIfKnown} to provide a more efficient 207 * implementation, it is <i>possible</i> that this method will return a different number of chars 208 * than would be returned by reading all of the chars. 209 * 210 * <p>In either case, for mutable sources such as files, a subsequent read may return a different 211 * number of chars if the contents are changed. 212 * 213 * @throws IOException if an I/O error occurs while reading the length of this source 214 * @since 19.0 215 */ 216 public long length() throws IOException { 217 Optional<Long> lengthIfKnown = lengthIfKnown(); 218 if (lengthIfKnown.isPresent()) { 219 return lengthIfKnown.get(); 220 } 221 222 Closer closer = Closer.create(); 223 try { 224 Reader reader = closer.register(openStream()); 225 return countBySkipping(reader); 226 } catch (Throwable e) { 227 throw closer.rethrow(e); 228 } finally { 229 closer.close(); 230 } 231 } 232 233 private long countBySkipping(Reader reader) throws IOException { 234 long count = 0; 235 long read; 236 while ((read = reader.skip(Long.MAX_VALUE)) != 0) { 237 count += read; 238 } 239 return count; 240 } 241 242 /** 243 * Appends the contents of this source to the given {@link Appendable} (such as a {@link Writer}). 244 * Does not close {@code appendable} if it is {@code Closeable}. 245 * 246 * @return the number of characters copied 247 * @throws IOException if an I/O error occurs while reading from this source or writing to {@code 248 * appendable} 249 */ 250 @CanIgnoreReturnValue 251 public long copyTo(Appendable appendable) throws IOException { 252 checkNotNull(appendable); 253 254 Closer closer = Closer.create(); 255 try { 256 Reader reader = closer.register(openStream()); 257 return CharStreams.copy(reader, appendable); 258 } catch (Throwable e) { 259 throw closer.rethrow(e); 260 } finally { 261 closer.close(); 262 } 263 } 264 265 /** 266 * Copies the contents of this source to the given sink. 267 * 268 * @return the number of characters copied 269 * @throws IOException if an I/O error occurs while reading from this source or writing to {@code 270 * sink} 271 */ 272 @CanIgnoreReturnValue 273 public long copyTo(CharSink sink) throws IOException { 274 checkNotNull(sink); 275 276 Closer closer = Closer.create(); 277 try { 278 Reader reader = closer.register(openStream()); 279 Writer writer = closer.register(sink.openStream()); 280 return CharStreams.copy(reader, writer); 281 } catch (Throwable e) { 282 throw closer.rethrow(e); 283 } finally { 284 closer.close(); 285 } 286 } 287 288 /** 289 * Reads the contents of this source as a string. 290 * 291 * @throws IOException if an I/O error occurs while reading from this source 292 */ 293 public String read() throws IOException { 294 Closer closer = Closer.create(); 295 try { 296 Reader reader = closer.register(openStream()); 297 return CharStreams.toString(reader); 298 } catch (Throwable e) { 299 throw closer.rethrow(e); 300 } finally { 301 closer.close(); 302 } 303 } 304 305 /** 306 * Reads the first line of this source as a string. Returns {@code null} if this source is empty. 307 * 308 * <p>Like {@link BufferedReader#readLine()}, this method considers a line to be a sequence of 309 * text that is terminated by (but does not include) one of {@code \r\n}, {@code \r} or {@code 310 * \n}. If the source's content does not end in a line termination sequence, it is treated as if 311 * it does. 312 * 313 * @throws IOException if an I/O error occurs while reading from this source 314 */ 315 @CheckForNull 316 public String readFirstLine() throws IOException { 317 Closer closer = Closer.create(); 318 try { 319 BufferedReader reader = closer.register(openBufferedStream()); 320 return reader.readLine(); 321 } catch (Throwable e) { 322 throw closer.rethrow(e); 323 } finally { 324 closer.close(); 325 } 326 } 327 328 /** 329 * Reads all the lines of this source as a list of strings. The returned list will be empty if 330 * this source is empty. 331 * 332 * <p>Like {@link BufferedReader#readLine()}, this method considers a line to be a sequence of 333 * text that is terminated by (but does not include) one of {@code \r\n}, {@code \r} or {@code 334 * \n}. If the source's content does not end in a line termination sequence, it is treated as if 335 * it does. 336 * 337 * @throws IOException if an I/O error occurs while reading from this source 338 */ 339 public ImmutableList<String> readLines() throws IOException { 340 Closer closer = Closer.create(); 341 try { 342 BufferedReader reader = closer.register(openBufferedStream()); 343 List<String> result = Lists.newArrayList(); 344 String line; 345 while ((line = reader.readLine()) != null) { 346 result.add(line); 347 } 348 return ImmutableList.copyOf(result); 349 } catch (Throwable e) { 350 throw closer.rethrow(e); 351 } finally { 352 closer.close(); 353 } 354 } 355 356 /** 357 * Reads lines of text from this source, processing each line as it is read using the given {@link 358 * LineProcessor processor}. Stops when all lines have been processed or the processor returns 359 * {@code false} and returns the result produced by the processor. 360 * 361 * <p>Like {@link BufferedReader#readLine()}, this method considers a line to be a sequence of 362 * text that is terminated by (but does not include) one of {@code \r\n}, {@code \r} or {@code 363 * \n}. If the source's content does not end in a line termination sequence, it is treated as if 364 * it does. 365 * 366 * @throws IOException if an I/O error occurs while reading from this source or if {@code 367 * processor} throws an {@code IOException} 368 * @since 16.0 369 */ 370 @CanIgnoreReturnValue // some processors won't return a useful result 371 @ParametricNullness 372 public <T extends @Nullable Object> T readLines(LineProcessor<T> processor) throws IOException { 373 checkNotNull(processor); 374 375 Closer closer = Closer.create(); 376 try { 377 Reader reader = closer.register(openStream()); 378 return CharStreams.readLines(reader, processor); 379 } catch (Throwable e) { 380 throw closer.rethrow(e); 381 } finally { 382 closer.close(); 383 } 384 } 385 386 /** 387 * Reads all lines of text from this source, running the given {@code action} for each line as it 388 * is read. 389 * 390 * <p>Like {@link BufferedReader#readLine()}, this method considers a line to be a sequence of 391 * text that is terminated by (but does not include) one of {@code \r\n}, {@code \r} or {@code 392 * \n}. If the source's content does not end in a line termination sequence, it is treated as if 393 * it does. 394 * 395 * @throws IOException if an I/O error occurs while reading from this source or if {@code action} 396 * throws an {@code UncheckedIOException} 397 * @since 22.0 (but only since 33.4.0 in the Android flavor) 398 */ 399 public void forEachLine(Consumer<? super String> action) throws IOException { 400 try (Stream<String> lines = lines()) { 401 // The lines should be ordered regardless in most cases, but use forEachOrdered to be sure 402 lines.forEachOrdered(action); 403 } catch (UncheckedIOException e) { 404 throw e.getCause(); 405 } 406 } 407 408 /** 409 * Returns whether the source has zero chars. The default implementation first checks {@link 410 * #lengthIfKnown}, returning true if it's known to be zero and false if it's known to be 411 * non-zero. If the length is not known, it falls back to opening a stream and checking for EOF. 412 * 413 * <p>Note that, in cases where {@code lengthIfKnown} returns zero, it is <i>possible</i> that 414 * chars are actually available for reading. This means that a source may return {@code true} from 415 * {@code isEmpty()} despite having readable content. 416 * 417 * @throws IOException if an I/O error occurs 418 * @since 15.0 419 */ 420 public boolean isEmpty() throws IOException { 421 Optional<Long> lengthIfKnown = lengthIfKnown(); 422 if (lengthIfKnown.isPresent()) { 423 return lengthIfKnown.get() == 0L; 424 } 425 Closer closer = Closer.create(); 426 try { 427 Reader reader = closer.register(openStream()); 428 return reader.read() == -1; 429 } catch (Throwable e) { 430 throw closer.rethrow(e); 431 } finally { 432 closer.close(); 433 } 434 } 435 436 /** 437 * Concatenates multiple {@link CharSource} instances into a single source. Streams returned from 438 * the source will contain the concatenated data from the streams of the underlying sources. 439 * 440 * <p>Only one underlying stream will be open at a time. Closing the concatenated stream will 441 * close the open underlying stream. 442 * 443 * @param sources the sources to concatenate 444 * @return a {@code CharSource} containing the concatenated data 445 * @since 15.0 446 */ 447 public static CharSource concat(Iterable<? extends CharSource> sources) { 448 return new ConcatenatedCharSource(sources); 449 } 450 451 /** 452 * Concatenates multiple {@link CharSource} instances into a single source. Streams returned from 453 * the source will contain the concatenated data from the streams of the underlying sources. 454 * 455 * <p>Only one underlying stream will be open at a time. Closing the concatenated stream will 456 * close the open underlying stream. 457 * 458 * <p>Note: The input {@code Iterator} will be copied to an {@code ImmutableList} when this method 459 * is called. This will fail if the iterator is infinite and may cause problems if the iterator 460 * eagerly fetches data for each source when iterated (rather than producing sources that only 461 * load data through their streams). Prefer using the {@link #concat(Iterable)} overload if 462 * possible. 463 * 464 * @param sources the sources to concatenate 465 * @return a {@code CharSource} containing the concatenated data 466 * @throws NullPointerException if any of {@code sources} is {@code null} 467 * @since 15.0 468 */ 469 public static CharSource concat(Iterator<? extends CharSource> sources) { 470 return concat(ImmutableList.copyOf(sources)); 471 } 472 473 /** 474 * Concatenates multiple {@link CharSource} instances into a single source. Streams returned from 475 * the source will contain the concatenated data from the streams of the underlying sources. 476 * 477 * <p>Only one underlying stream will be open at a time. Closing the concatenated stream will 478 * close the open underlying stream. 479 * 480 * @param sources the sources to concatenate 481 * @return a {@code CharSource} containing the concatenated data 482 * @throws NullPointerException if any of {@code sources} is {@code null} 483 * @since 15.0 484 */ 485 public static CharSource concat(CharSource... sources) { 486 return concat(ImmutableList.copyOf(sources)); 487 } 488 489 /** 490 * Returns a view of the given character sequence as a {@link CharSource}. The behavior of the 491 * returned {@code CharSource} and any {@code Reader} instances created by it is unspecified if 492 * the {@code charSequence} is mutated while it is being read, so don't do that. 493 * 494 * @since 15.0 (since 14.0 as {@code CharStreams.asCharSource(String)}) 495 */ 496 public static CharSource wrap(CharSequence charSequence) { 497 return charSequence instanceof String 498 ? new StringCharSource((String) charSequence) 499 : new CharSequenceCharSource(charSequence); 500 } 501 502 /** 503 * Returns an immutable {@link CharSource} that contains no characters. 504 * 505 * @since 15.0 506 */ 507 public static CharSource empty() { 508 return EmptyCharSource.INSTANCE; 509 } 510 511 /** A byte source that reads chars from this source and encodes them as bytes using a charset. */ 512 private final class AsByteSource extends ByteSource { 513 514 final Charset charset; 515 516 AsByteSource(Charset charset) { 517 this.charset = checkNotNull(charset); 518 } 519 520 @Override 521 public CharSource asCharSource(Charset charset) { 522 if (charset.equals(this.charset)) { 523 return CharSource.this; 524 } 525 return super.asCharSource(charset); 526 } 527 528 @Override 529 public InputStream openStream() throws IOException { 530 return new ReaderInputStream(CharSource.this.openStream(), charset, 8192); 531 } 532 533 @Override 534 public String toString() { 535 return CharSource.this.toString() + ".asByteSource(" + charset + ")"; 536 } 537 } 538 539 private static class CharSequenceCharSource extends CharSource { 540 541 private static final Splitter LINE_SPLITTER = Splitter.onPattern("\r\n|\n|\r"); 542 543 protected final CharSequence seq; 544 545 protected CharSequenceCharSource(CharSequence seq) { 546 this.seq = checkNotNull(seq); 547 } 548 549 @Override 550 public Reader openStream() { 551 return new CharSequenceReader(seq); 552 } 553 554 @Override 555 public String read() { 556 return seq.toString(); 557 } 558 559 @Override 560 public boolean isEmpty() { 561 return seq.length() == 0; 562 } 563 564 @Override 565 public long length() { 566 return seq.length(); 567 } 568 569 @Override 570 public Optional<Long> lengthIfKnown() { 571 return Optional.of((long) seq.length()); 572 } 573 574 /** 575 * Returns an iterator over the lines in the string. If the string ends in a newline, a final 576 * empty string is not included, to match the behavior of BufferedReader/LineReader.readLine(). 577 */ 578 private Iterator<String> linesIterator() { 579 return new AbstractIterator<String>() { 580 Iterator<String> lines = LINE_SPLITTER.split(seq).iterator(); 581 582 @Override 583 @CheckForNull 584 protected String computeNext() { 585 if (lines.hasNext()) { 586 String next = lines.next(); 587 // skip last line if it's empty 588 if (lines.hasNext() || !next.isEmpty()) { 589 return next; 590 } 591 } 592 return endOfData(); 593 } 594 }; 595 } 596 597 @Override 598 public Stream<String> lines() { 599 return stream(linesIterator()); 600 } 601 602 @Override 603 @CheckForNull 604 public String readFirstLine() { 605 Iterator<String> lines = linesIterator(); 606 return lines.hasNext() ? lines.next() : null; 607 } 608 609 @Override 610 public ImmutableList<String> readLines() { 611 return ImmutableList.copyOf(linesIterator()); 612 } 613 614 @Override 615 @ParametricNullness 616 public <T extends @Nullable Object> T readLines(LineProcessor<T> processor) throws IOException { 617 Iterator<String> lines = linesIterator(); 618 while (lines.hasNext()) { 619 if (!processor.processLine(lines.next())) { 620 break; 621 } 622 } 623 return processor.getResult(); 624 } 625 626 @Override 627 public String toString() { 628 return "CharSource.wrap(" + Ascii.truncate(seq, 30, "...") + ")"; 629 } 630 } 631 632 /** 633 * Subclass specialized for string instances. 634 * 635 * <p>Since Strings are immutable and built into the jdk we can optimize some operations 636 * 637 * <ul> 638 * <li>use {@link StringReader} instead of {@link CharSequenceReader}. It is faster since it can 639 * use {@link String#getChars(int, int, char[], int)} instead of copying characters one by 640 * one with {@link CharSequence#charAt(int)}. 641 * <li>use {@link Appendable#append(CharSequence)} in {@link #copyTo(Appendable)} and {@link 642 * #copyTo(CharSink)}. We know this is correct since strings are immutable and so the length 643 * can't change, and it is faster because many writers and appendables are optimized for 644 * appending string instances. 645 * </ul> 646 */ 647 private static class StringCharSource extends CharSequenceCharSource { 648 protected StringCharSource(String seq) { 649 super(seq); 650 } 651 652 @Override 653 public Reader openStream() { 654 return new StringReader((String) seq); 655 } 656 657 @Override 658 public long copyTo(Appendable appendable) throws IOException { 659 appendable.append(seq); 660 return seq.length(); 661 } 662 663 @Override 664 public long copyTo(CharSink sink) throws IOException { 665 checkNotNull(sink); 666 Closer closer = Closer.create(); 667 try { 668 Writer writer = closer.register(sink.openStream()); 669 writer.write((String) seq); 670 return seq.length(); 671 } catch (Throwable e) { 672 throw closer.rethrow(e); 673 } finally { 674 closer.close(); 675 } 676 } 677 } 678 679 private static final class EmptyCharSource extends StringCharSource { 680 681 private static final EmptyCharSource INSTANCE = new EmptyCharSource(); 682 683 private EmptyCharSource() { 684 super(""); 685 } 686 687 @Override 688 public String toString() { 689 return "CharSource.empty()"; 690 } 691 } 692 693 private static final class ConcatenatedCharSource extends CharSource { 694 695 private final Iterable<? extends CharSource> sources; 696 697 ConcatenatedCharSource(Iterable<? extends CharSource> sources) { 698 this.sources = checkNotNull(sources); 699 } 700 701 @Override 702 public Reader openStream() throws IOException { 703 return new MultiReader(sources.iterator()); 704 } 705 706 @Override 707 public boolean isEmpty() throws IOException { 708 for (CharSource source : sources) { 709 if (!source.isEmpty()) { 710 return false; 711 } 712 } 713 return true; 714 } 715 716 @Override 717 public Optional<Long> lengthIfKnown() { 718 long result = 0L; 719 for (CharSource source : sources) { 720 Optional<Long> lengthIfKnown = source.lengthIfKnown(); 721 if (!lengthIfKnown.isPresent()) { 722 return Optional.absent(); 723 } 724 result += lengthIfKnown.get(); 725 } 726 return Optional.of(result); 727 } 728 729 @Override 730 public long length() throws IOException { 731 long result = 0L; 732 for (CharSource source : sources) { 733 result += source.length(); 734 } 735 return result; 736 } 737 738 @Override 739 public String toString() { 740 return "CharSource.concat(" + sources + ")"; 741 } 742 } 743}