Interface Source
-
- All Superinterfaces:
AutoCloseable,Closeable
- All Known Subinterfaces:
BufferedSource
- All Known Implementing Classes:
Buffer,ForwardingSource,GzipSource,InflaterSource
public interface Source extends 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
BufferedSourcewhich is both more efficient and more convenient. UseOkio.buffer(Source)to wrap any source with a buffer.Sources are easy to test: just use an
Bufferin your tests, and fill it with the data your application is to read.Comparison with InputStream
This interface is functionally equivalent toInputStream.InputStreamrequires multiple layers when consumed data is heterogeneous: aDataInputStreamfor primitive values, aBufferedInputStreamfor buffering, andInputStreamReaderfor strings. This class usesBufferedSourcefor 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
InputStream; callers instead just buffer what they need.When implementing a source, you need not worry about the single-byte read method that is awkward to implement efficiently and that returns one of 257 possible values.
And source has a stronger
skipmethod:BufferedSource.skip(long)won't return prematurely.Interop with InputStream
UseOkio.source(java.io.InputStream)to adapt anInputStreamto a source. UseBufferedSource.inputStream()to adapt a source to anInputStream.
-
-
Method Summary
All Methods Instance Methods Abstract Methods Modifier and Type Method Description voidclose()Closes this source and releases the resources held by this source.longread(Buffer sink, long byteCount)Removes at least 1, and up tobyteCountbytes from this and appends them tosink.Timeouttimeout()Returns the timeout for this source.
-
-
-
Method Detail
-
read
long read(Buffer sink, long byteCount) throws IOException
Removes at least 1, and up tobyteCountbytes from this and appends them tosink. Returns the number of bytes read, or -1 if this source is exhausted.- Throws:
IOException
-
timeout
Timeout timeout()
Returns the timeout for this source.
-
close
void close() throws IOExceptionCloses this source and releases the resources held by this source. It is an error to read a closed source. It is safe to close a source more than once.- Specified by:
closein interfaceAutoCloseable- Specified by:
closein interfaceCloseable- Throws:
IOException
-
-