-
- All Implemented Interfaces:
-
java.io.Closeable,java.lang.AutoCloseable
public interface Source implements Closeable
Supplies a stream of bytes. Use this interface to read data from wherever it's located: from the network, storage, or a buffer in memory. Sources may be layered to transform supplied data, such as to decompress, decrypt, or remove protocol framing.
Most applications shouldn't operate on a source directly, but rather on a BufferedSource which is both more efficient and more convenient. Use buffer to wrap any source with a buffer.
Sources are easy to test: just use a Buffer in your tests, and fill it with the data your application is to read.
Comparison with InputStreamThis interface is functionally equivalent to java.io.InputStream.{@code InputStream}requires multiple layers when consumed data is heterogeneous: a{@code DataInputStream}for primitive values, a{@code * BufferedInputStream}for buffering, and{@code InputStreamReader}for strings. This class uses{@code BufferedSource}for all of the above.Source avoids the impossible-to-implement available() method. Instead callers specify how many bytes they require.
Source omits the unsafe-to-compose mark and reset state that's tracked by
{@code InputStream}; instead, callers just buffer what they need.When implementing a source, you don't need to worry about the single-byte read method that is awkward to implement efficiently and returns one of 257 possible values.
And source has a stronger
Interop with InputStreamUse source to adapt an{@code skip}method: skip won't return prematurely.{@code InputStream}to a source. Use inputStream to adapt a source to an{@code * InputStream}.
-
-
Method Summary
Modifier and Type Method Description abstract longread(Buffer sink, long byteCount)Removes at least 1, and up to {@code byteCount}bytes from this and appendsthem to{@code sink}.abstract Timeouttimeout()Returns the timeout for this source. abstract voidclose()Closes this source and releases the resources held by this source. -
-
Method Detail
-
read
abstract long read(Buffer sink, long byteCount)
Removes at least 1, and up to
{@code byteCount}bytes from this and appendsthem to{@code sink}. Returns the number of bytes read, or -1 if thissource is exhausted.
-
close
abstract void close()
Closes this source and releases the resources held by this source. It is anerror to read a closed source. It is safe to close a source more than once.
-
-
-
-