Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * Copyright (C) 2012 The Guava Authors
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   * http://www.apache.org/licenses/LICENSE-2.0
   *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
 
 package com.google.common.io;
 
 import static com.google.common.base.Preconditions.checkNotNull;
 
 
 import java.io.Reader;
 import java.io.Writer;
 import java.util.List;
 
A readable source of characters, such as a text file. Unlike a java.io.Reader, a CharSource is not an open, stateful stream of characters that can be read and closed. Instead, it is an immutable supplier of Reader instances.

CharSource provides two kinds of methods:

  • Methods that return a reader: These methods should return a new, independent instance each time they are called. The caller is responsible for ensuring that the returned reader is closed.
  • Convenience methods: These are implementations of common operations that are typically implemented by opening a reader using one of the methods in the first category, doing something and finally closing the reader that was opened.

Several methods in this class, such as readLines(), break the contents of the source into lines. Like java.io.BufferedReader, these methods break lines on any of \n, \r or \r\n, do not include the line separator in each line and do not consider there to be an empty line at the end if the contents are terminated with a line separator.

Any ByteSource containing text encoded with a specific character encoding may be viewed as a CharSource using ByteSource.asCharSource(java.nio.charset.Charset).

Author(s):
Colin Decker
Since:
14.0
 
 public abstract class CharSource implements InputSupplier<Reader> {

  
Opens a new java.io.Reader for reading from this source. This method should return a new, independent reader each time it is called.

The caller is responsible for ensuring that the returned reader is closed.

Throws:
java.io.IOException if an I/O error occurs in the process of opening the reader
 
   public abstract Reader openStream() throws IOException;

  
This method is a temporary method provided for easing migration from suppliers to sources and sinks.

Deprecated:
This method is only provided for temporary compatibility with the InputSupplier interface and should not be called directly. Use openStream() instead.
Since:
15.0
 
   @Override
   public final Reader getInput() throws IOException {
     return openStream();
   }

  
Opens a new java.io.BufferedReader for reading from this source. This method should return a new, independent reader each time it is called.

The caller is responsible for ensuring that the returned reader is closed.

Throws:
java.io.IOException if an I/O error occurs in the process of opening the reader
 
   public BufferedReader openBufferedStream() throws IOException {
     Reader reader = openStream();
    return (reader instanceof BufferedReader)
        ? (BufferedReaderreader
        : new BufferedReader(reader);
  }

  
Appends the contents of this source to the given java.lang.Appendable (such as a java.io.Writer). Does not close appendable if it is Closeable.

Throws:
java.io.IOException if an I/O error occurs in the process of reading from this source or writing to appendable
  public long copyTo(Appendable appendablethrows IOException {
    checkNotNull(appendable);
    Closer closer = Closer.create();
    try {
      Reader reader = closer.register(openStream());
      return CharStreams.copy(readerappendable);
    } catch (Throwable e) {
      throw closer.rethrow(e);
    } finally {
      closer.close();
    }
  }

  
Copies the contents of this source to the given sink.

Throws:
java.io.IOException if an I/O error occurs in the process of reading from this source or writing to sink
  public long copyTo(CharSink sinkthrows IOException {
    checkNotNull(sink);
    Closer closer = Closer.create();
    try {
      Reader reader = closer.register(openStream());
      Writer writer = closer.register(sink.openStream());
      return CharStreams.copy(readerwriter);
    } catch (Throwable e) {
      throw closer.rethrow(e);
    } finally {
      closer.close();
    }
  }

  
Reads the contents of this source as a string.

Throws:
java.io.IOException if an I/O error occurs in the process of reading from this source
  public String read() throws IOException {
    Closer closer = Closer.create();
    try {
      Reader reader = closer.register(openStream());
      return CharStreams.toString(reader);
    } catch (Throwable e) {
      throw closer.rethrow(e);
    } finally {
      closer.close();
    }
  }

  
Reads the first link of this source as a string. Returns null if this source is empty.

Like java.io.BufferedReader, this method breaks lines on any of \n, \r or \r\n, does not include the line separator in the returned line and does not consider there to be an extra empty line at the end if the content is terminated with a line separator.

Throws:
java.io.IOException if an I/O error occurs in the process of reading from this source
  public @Nullable String readFirstLine() throws IOException {
    Closer closer = Closer.create();
    try {
      BufferedReader reader = closer.register(openBufferedStream());
      return reader.readLine();
    } catch (Throwable e) {
      throw closer.rethrow(e);
    } finally {
      closer.close();
    }
  }

  
Reads all the lines of this source as a list of strings. The returned list will be empty if this source is empty.

Like java.io.BufferedReader, this method breaks lines on any of \n, \r or \r\n, does not include the line separator in the returned lines and does not consider there to be an extra empty line at the end if the content is terminated with a line separator.

Throws:
java.io.IOException if an I/O error occurs in the process of reading from this source
  public ImmutableList<StringreadLines() throws IOException {
    Closer closer = Closer.create();
    try {
      BufferedReader reader = closer.register(openBufferedStream());
      List<Stringresult = Lists.newArrayList();
      String line;
      while ((line = reader.readLine()) != null) {
        result.add(line);
      }
      return ImmutableList.copyOf(result);
    } catch (Throwable e) {
      throw closer.rethrow(e);
    } finally {
      closer.close();
    }
  }

  
Returns whether the source has zero chars. The default implementation is to open a stream and check for EOF.

Throws:
java.io.IOException if an I/O error occurs
Since:
15.0
  public boolean isEmpty() throws IOException {
    Closer closer = Closer.create();
    try {
      Reader reader = closer.register(openStream());
      return reader.read() == -1;
    } catch (Throwable e) {
      throw closer.rethrow(e);
    } finally {
      closer.close();
    }
  }

  
Concatenates multiple CharSource instances into a single source. Streams returned from the source will contain the concatenated data from the streams of the underlying sources.

Only one underlying stream will be open at a time. Closing the concatenated stream will close the open underlying stream.

Parameters:
sources the sources to concatenate
Returns:
a CharSource containing the concatenated data
Since:
15.0
  public static CharSource concat(Iterable<? extends CharSourcesources) {
    return new ConcatenatedCharSource(sources);
  }

  
Concatenates multiple CharSource instances into a single source. Streams returned from the source will contain the concatenated data from the streams of the underlying sources.

Only one underlying stream will be open at a time. Closing the concatenated stream will close the open underlying stream.

Note: The input Iterator will be copied to an ImmutableList when this method is called. This will fail if the iterator is infinite and may cause problems if the iterator eagerly fetches data for each source when iterated (rather than producing sources that only load data through their streams). Prefer using the concat(java.lang.Iterable) overload if possible.

Parameters:
sources the sources to concatenate
Returns:
a CharSource containing the concatenated data
Throws:
java.lang.NullPointerException if any of sources is null
Since:
15.0
  public static CharSource concat(Iterator<? extends CharSourcesources) {
    return concat(ImmutableList.copyOf(sources));
  }

  
Concatenates multiple CharSource instances into a single source. Streams returned from the source will contain the concatenated data from the streams of the underlying sources.

Only one underlying stream will be open at a time. Closing the concatenated stream will close the open underlying stream.

Parameters:
sources the sources to concatenate
Returns:
a CharSource containing the concatenated data
Throws:
java.lang.NullPointerException if any of sources is null
Since:
15.0
  public static CharSource concat(CharSource... sources) {
    return concat(ImmutableList.copyOf(sources));
  }

  
Returns a view of the given character sequence as a CharSource. The behavior of the returned CharSource and any Reader instances created by it is unspecified if the charSequence is mutated while it is being read, so don't do that.

Since:
15.0 (since 14.0 as CharStreams.asCharSource(String))
  public static CharSource wrap(CharSequence charSequence) {
    return new CharSequenceCharSource(charSequence);
  }

  
Returns an immutable CharSource that contains no characters.

Since:
15.0
  public static CharSource empty() {
    return .;
  }
  private static class CharSequenceCharSource extends CharSource {
    private static final Splitter LINE_SPLITTER
        = Splitter.on(Pattern.compile("\r\n|\n|\r"));
    private final CharSequence seq;
    protected CharSequenceCharSource(CharSequence seq) {
      this. = checkNotNull(seq);
    }
    @Override
    public Reader openStream() {
      return new CharSequenceReader();
    }
    @Override
    public String read() {
      return .toString();
    }
    @Override
    public boolean isEmpty() {
      return .length() == 0;
    }

    
Returns an iterable over the lines in the string. If the string ends in a newline, a final empty string is not included to match the behavior of BufferedReader/LineReader.readLine().
    private Iterable<Stringlines() {
      return new Iterable<String>() {
        @Override
        public Iterator<Stringiterator() {
          return new AbstractIterator<String>() {
            Iterator<Stringlines = .split().iterator();
            @Override
            protected String computeNext() {
              if (.hasNext()) {
                String next = .next();
                // skip last line if it's empty
                if (.hasNext() || !next.isEmpty()) {
                  return next;
                }
              }
              return endOfData();
            }
          };
        }
      };
    }
    @Override
    public String readFirstLine() {
      Iterator<Stringlines = lines().iterator();
      return lines.hasNext() ? lines.next() : null;
    }
    @Override
    public ImmutableList<StringreadLines() {
      return ImmutableList.copyOf(lines());
    }
    @Override
    public String toString() {
      CharSequence shortened = (.length() <= 15) ?  : .subSequence(0, 12) + "...";
      return "CharSource.wrap(" + shortened + ")";
    }
  }
  private static final class EmptyCharSource extends CharSequenceCharSource {
    private static final EmptyCharSource INSTANCE = new EmptyCharSource();
    private EmptyCharSource() {
      super("");
    }
    @Override
    public String toString() {
      return "CharSource.empty()";
    }
  }
  private static final class ConcatenatedCharSource extends CharSource {
    private final Iterable<? extends CharSourcesources;
    ConcatenatedCharSource(Iterable<? extends CharSourcesources) {
      this. = checkNotNull(sources);
    }
    @Override
    public Reader openStream() throws IOException {
      return new MultiReader(.iterator());
    }
    @Override
    public boolean isEmpty() throws IOException {
      for (CharSource source : ) {
        if (!source.isEmpty()) {
          return false;
        }
      }
      return true;
    }
    @Override
    public String toString() {
      return "CharSource.concat(" +  + ")";
    }
  }
New to GrepCode? Check out our FAQ X