實際上,有一個專門用於處理輸入流等資源的源代碼。這就是所謂的Source.unfoldResource
:
Source<ByteString, NotUsed> source = Source.unfoldResource(
() -> prepareEncryptedStream(),
is -> readChunk(is, 4096),
InputStream::close
);
Optional<ByteString> readChunk(InputStream is, int size) throws IOException {
byte[] data = new byte[size];
int read = is.read(data);
if (read < 0) {
return Optional.empty();
}
return Optional.of(ByteString.fromArray(data, 0, read));
}
InputStream prepareEncryptedStream() { ... }
這裏prepareCompressedFile()
是應該回到你想創建一個反應流加密流的方法,並readChunk()
是一個便捷方法讀取指定大小的InputStream
一個ByteString
。
如果您可以將壓縮和加密例程表示爲ByteString -> ByteString
函數,那麼您並不需要這些;所有你需要做的就是將這些程序傳遞給map()
流量:
Source<ByteString, CompletionStage<IOResult>> source =
FileIO.fromPath(Paths.get("somewhere"))
.map(bs -> compress(bs))
.map(bs -> encrypt(bs));
ByteString encrypt(ByteString bs) { ... }
ByteString compress(ByteString bs) { ... }
我認爲你應該接受你自己的答案,而不是我的,因爲它解決了問題,你的問題在很多更好的方式。 –