Sources and sinks are objects that know how to open streams.
Bytes | Chars | |
---|---|---|
Reading | ByteSource | CharSource |
Writing | ByteSink | CharSink |
Note: for all examples, consider UTF_8
as if the following import is set:
import static java.nio.charset.StandardCharsets.UTF_8;
ByteSource dataSource = Files.asByteSource(new File("input.dat"));
CharSource textSource = Files.asCharSource(new File("input.txt"), UTF_8);
ByteSink dataSink = Files.asByteSink(new File("output.dat"));
CharSink textSink = Files.asCharSink(new File("output.txt"), UTF_8);
ByteSource dataSource = Resources.asByteSource(url);
CharSource textSource = Resources.asCharSource(url, UTF_8);
ByteSource dataSource = ByteSource.wrap(new byte[] {1, 2, 3});
CharSource textSource = CharSource.wrap("abc");
ByteSource originalSource = ...
CharSource textSource = originalSource.asCharSource(UTF_8);
(From Guava 20 onwards)
CharSource originalSource = ...
ByteSource dataSource = originalSource.asByteSource(UTF_8);
Opening a stream
InputStream inputStream = byteSource.openStream();
OutputStream outputStream = byteSink.openStream();
Reader reader = charSource.openStream();
Writer writer = charSink.openStream();
Opening a buffered stream
InputStream bufferedInputStream = byteSource.openBufferedStream();
OutputStream bufferedOutputStream = byteSink.openBufferedStream();
BufferedReader bufferedReader = charSource.openBufferedStream();
Writer bufferedWriter = charSink.openBufferedStream();
Reading from a source:
ByteSource source = ...
byte[] bytes = source.read();
CharSource source = ...
String text = source.read();
Reading lines from a source:
CharSource source = ...
ImmutableList<String> lines = source.readLines();
Reading the first line from a source:
CharSource source = ...
String firstLine = source.readFirstLine();
Copying from a source to a sink:
ByteSource source = ...
ByteSink sink = ...
source.copyTo(sink);
CharSource source = ...
CharSink sink = ...
source.copyTo(sink);
CharSource source = ...
try (Reader reader = source.openStream()) {
// use the reader
}