來源和匯

源和接收器是知道如何開啟流的物件。

位元組 個字元
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
}