StreamConverters.fromOutputStream
Create a sink that wraps an OutputStream
.
Additional Sink and Source converters
Signature
StreamConverters.fromOutputStream
StreamConverters.fromOutputStream
Description
Creates a Sink which writes incoming ByteString
ByteString
s to a java.io.OutputStream
created by the given function.
Materializes a CompletionStage
Future
of IOResult
that will be completed with the size of the file (in bytes) on completion, and a possible exception if IO operation was not completed successfully.
You can configure the default dispatcher for this Source by changing the akka.stream.materializer.blocking-io-dispatcher
or set it for a given Source by using akka.stream.ActorAttributes
.
If autoFlush
is true the OutputStream will be flushed whenever a byte array is written, defaults to false. The OutputStream
will be closed when the stream flowing into this Sink
is completed. The Sink
will cancel the stream when the OutputStream
is no longer writable.
See also fromInputStream
Example
Here is an example using both fromInputStream
and fromOutputStream
to read from a java.io.InputStream
, uppercase the read content and write back out into a java.io.OutputStream
.
- Scala
-
source
val bytes = "Some random input".getBytes val inputStream = new ByteArrayInputStream(bytes) val outputStream = new ByteArrayOutputStream() val source: Source[ByteString, Future[IOResult]] = StreamConverters.fromInputStream(() => inputStream) val toUpperCase: Flow[ByteString, ByteString, NotUsed] = Flow[ByteString].map(_.map(_.toChar.toUpper.toByte)) val sink: Sink[ByteString, Future[IOResult]] = StreamConverters.fromOutputStream(() => outputStream) val eventualResult = source.via(toUpperCase).runWith(sink)
- Java
-
source
java.io.InputStream inputStream = new ByteArrayInputStream(bytes); Source<ByteString, CompletionStage<IOResult>> source = StreamConverters.fromInputStream(() -> inputStream); // Given a ByteString produces a ByteString with the upperCase representation // Removed from the sample for brevity. // Flow<ByteString, ByteString, NotUsed> toUpperCase = ... java.io.OutputStream outputStream = new ByteArrayOutputStream(); Sink<ByteString, CompletionStage<IOResult>> sink = StreamConverters.fromOutputStream(() -> outputStream); CompletionStage<IOResult> ioResultCompletionStage = source.via(toUpperCase).runWith(sink, system); // When the ioResultCompletionStage completes, the byte array backing the outputStream // will contain the uppercase representation of the bytes read from the inputStream.