Class CharSource
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 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(Charset).
Note: In general, CharSource is intended to be used for "file-like" sources
that provide readers that are:
- Finite: Many operations, such as
length()andread(), will either block indefinitely or fail if the source creates an infinite reader. - Non-destructive: A destructive reader will consume or otherwise alter the
source as they are read from it. A source that provides such readers will not be reusable,
and operations that read from the stream (including
length(), in some implementations) will prevent further operations from completing as expected.
- Since:
- 14.0
- Author:
- Colin Decker
-
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionasByteSource(Charset charset) Returns aByteSourceview of this char source that encodes chars read from this source as bytes using the givenCharset.static CharSourceconcat(CharSource... sources) Concatenates multipleCharSourceinstances into a single source.static CharSourceconcat(Iterable<? extends CharSource> sources) Concatenates multipleCharSourceinstances into a single source.static CharSourceconcat(Iterator<? extends CharSource> sources) Concatenates multipleCharSourceinstances into a single source.longCopies the contents of this source to the given sink.longcopyTo(Appendable appendable) Appends the contents of this source to the givenAppendable(such as aWriter).static CharSourceempty()Returns an immutableCharSourcethat contains no characters.voidforEachLine(Consumer<? super String> action) Reads all lines of text from this source, running the givenactionfor each line as it is read.booleanisEmpty()Returns whether the source has zero chars.longlength()Returns the length of this source in chars, even if doing so requires opening and traversing an entire stream.Returns the size of this source in chars, if the size can be easily determined without actually opening the data stream.lines()Opens a newStreamfor reading text one line at a time from this source.Opens a newBufferedReaderfor reading from this source.abstract ReaderOpens a newReaderfor reading from this source.read()Reads the contents of this source as a string.Reads the first line of this source as a string.Reads all the lines of this source as a list of strings.readLines(LineProcessor<T> processor) Reads lines of text from this source, processing each line as it is read using the givenprocessor.static CharSourcewrap(CharSequence charSequence) Returns a view of the given character sequence as aCharSource.
-
Constructor Details
-
CharSource
protected CharSource()Constructor for use by subclasses.
-
-
Method Details
-
asByteSource
Returns aByteSourceview of this char source that encodes chars read from this source as bytes using the givenCharset.If
ByteSource.asCharSource(Charset)is called on the returned source with the same charset, the default implementation of this method will ensure that the originalCharSourceis returned, rather than round-trip encoding. Subclasses that override this method should behave the same way.- Since:
- 20.0
-
openStream
Opens a newReaderfor reading from this source. This method returns a new, independent reader each time it is called.The caller is responsible for ensuring that the returned reader is closed.
- Throws:
IOException- if an I/O error occurs while opening the reader
-
openBufferedStream
Opens a newBufferedReaderfor reading from this source. This method returns a new, independent reader each time it is called.The caller is responsible for ensuring that the returned reader is closed.
- Throws:
IOException- if an I/O error occurs while of opening the reader
-
lines
Opens a newStreamfor reading text one line at a time from this source. This method returns a new, independent stream each time it is called.The returned stream is lazy and only reads from the source in the terminal operation. If an I/O error occurs while the stream is reading from the source or when the stream is closed, an
UncheckedIOExceptionis thrown.Like
BufferedReader.readLine(), this method considers a line to be a sequence of text that is terminated by (but does not include) one of\r\n,\ror\n. If the source's content does not end in a line termination sequence, it is treated as if it does.The caller is responsible for ensuring that the returned stream is closed. For example:
try (Stream<String> lines = source.lines()) { lines.map(...) .filter(...) .forEach(...); }- Throws:
IOException- if an I/O error occurs while opening the stream- Since:
- 22.0 (but only since 33.4.0 in the Android flavor)
-
lengthIfKnown
Returns the size of this source in chars, if the size can be easily determined without actually opening the data stream.The default implementation returns
Optional.absent(). Some sources, such as aCharSequence, may return a non-absent value. Note that in such cases, it is possible that this method will return a different number of chars than would be returned by reading all of the chars.Additionally, for mutable sources such as
StringBuilders, a subsequent read may return a different number of chars if the contents are changed.- Since:
- 19.0
-
length
Returns the length of this source in chars, even if doing so requires opening and traversing an entire stream. To avoid a potentially expensive operation, seelengthIfKnown().The default implementation calls
lengthIfKnown()and returns the value if present. If absent, it will fall back to a heavyweight operation that will open a stream,skipto the end of the stream, and return the total number of chars that were skipped.Note that for sources that implement
lengthIfKnown()to provide a more efficient implementation, it is possible that this method will return a different number of chars than would be returned by reading all of the chars.In either case, for mutable sources such as files, a subsequent read may return a different number of chars if the contents are changed.
- Throws:
IOException- if an I/O error occurs while reading the length of this source- Since:
- 19.0
-
copyTo
Appends the contents of this source to the givenAppendable(such as aWriter). Does not closeappendableif it isCloseable.- Returns:
- the number of characters copied
- Throws:
IOException- if an I/O error occurs while reading from this source or writing toappendable
-
copyTo
Copies the contents of this source to the given sink.- Returns:
- the number of characters copied
- Throws:
IOException- if an I/O error occurs while reading from this source or writing tosink
-
read
Reads the contents of this source as a string.- Throws:
IOException- if an I/O error occurs while reading from this source
-
readFirstLine
Reads the first line of this source as a string. Returnsnullif this source is empty.Like
BufferedReader.readLine(), this method considers a line to be a sequence of text that is terminated by (but does not include) one of\r\n,\ror\n. If the source's content does not end in a line termination sequence, it is treated as if it does.- Throws:
IOException- if an I/O error occurs while reading from this source
-
readLines
Reads all the lines of this source as a list of strings. The returned list will be empty if this source is empty.Like
BufferedReader.readLine(), this method considers a line to be a sequence of text that is terminated by (but does not include) one of\r\n,\ror\n. If the source's content does not end in a line termination sequence, it is treated as if it does.- Throws:
IOException- if an I/O error occurs while reading from this source
-
readLines
@CanIgnoreReturnValue public <T extends @Nullable Object> T readLines(LineProcessor<T> processor) throws IOException Reads lines of text from this source, processing each line as it is read using the givenprocessor. Stops when all lines have been processed or the processor returnsfalseand returns the result produced by the processor.Like
BufferedReader.readLine(), this method considers a line to be a sequence of text that is terminated by (but does not include) one of\r\n,\ror\n. If the source's content does not end in a line termination sequence, it is treated as if it does.- Throws:
IOException- if an I/O error occurs while reading from this source or ifprocessorthrows anIOException- Since:
- 16.0
-
forEachLine
Reads all lines of text from this source, running the givenactionfor each line as it is read.Like
BufferedReader.readLine(), this method considers a line to be a sequence of text that is terminated by (but does not include) one of\r\n,\ror\n. If the source's content does not end in a line termination sequence, it is treated as if it does.- Throws:
IOException- if an I/O error occurs while reading from this source or ifactionthrows anUncheckedIOException- Since:
- 22.0 (but only since 33.4.0 in the Android flavor)
-
isEmpty
Returns whether the source has zero chars. The default implementation first checkslengthIfKnown(), returning true if it's known to be zero and false if it's known to be non-zero. If the length is not known, it falls back to opening a stream and checking for EOF.Note that, in cases where
lengthIfKnownreturns zero, it is possible that chars are actually available for reading. This means that a source may returntruefromisEmpty()despite having readable content.- Throws:
IOException- if an I/O error occurs- Since:
- 15.0
-
concat
Concatenates multipleCharSourceinstances 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
CharSourcecontaining the concatenated data - Since:
- 15.0
-
concat
Concatenates multipleCharSourceinstances 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
Iteratorwill be copied to anImmutableListwhen 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 theconcat(Iterable)overload if possible.- Parameters:
sources- the sources to concatenate- Returns:
- a
CharSourcecontaining the concatenated data - Throws:
NullPointerException- if any ofsourcesisnull- Since:
- 15.0
-
concat
Concatenates multipleCharSourceinstances 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
CharSourcecontaining the concatenated data - Throws:
NullPointerException- if any ofsourcesisnull- Since:
- 15.0
-
wrap
Returns a view of the given character sequence as aCharSource. The behavior of the returnedCharSourceand anyReaderinstances created by it is unspecified if thecharSequenceis mutated while it is being read, so don't do that.- Since:
- 15.0 (since 14.0 as
CharStreams.asCharSource(String))
-
empty
Returns an immutableCharSourcethat contains no characters.- Since:
- 15.0
-