来源和汇

源和接收器是知道如何打开流的对象。

字节 个字符
ByteSource CharSource
写作 ByteSink CharSink

创建源和汇

注意:对于所有示例,请考虑 UTF_8,就像设置了以下导入一样:

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);

从 URL 读取

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);

从字符转换为字节

(从番石榴 20 开始)

CharSource originalSource = ...
ByteSource dataSource = originalSource.asByteSource(UTF_8);

使用源和汇

常见的操作

打开一个流

InputStream inputStream = byteSource.openStream();
OutputStream outputStream = byteSink.openStream();
Reader reader = charSource.openStream();
Writer writer = charSink.openStream();

打开缓冲流

InputStream bufferedInputStream = byteSource.openBufferedStream();
OutputStream bufferedOutputStream = byteSink.openBufferedStream();
BufferedReader bufferedReader = charSource.openBufferedStream();
Writer bufferedWriter = charSink.openBufferedStream();

来源业务

从来源阅读:

ByteSource source = ...
byte[] bytes = source.read();

CharSource source = ...
String text = source.read();

从源读取行:

CharSource source = ...
ImmutableList<String> lines = source.readLines();

从源读取第一行:

CharSource source = ...
String firstLine = source.readFirstLine();

从源复制到接收器:

ByteSource source = ...
ByteSink sink = ...
source.copyTo(sink);

CharSource source = ...
CharSink sink = ...
source.copyTo(sink);

典型用法

CharSource source = ...
try (Reader reader = source.openStream()) {
  // use the reader
}