I have some data streamed from different files. It is in the following format:
Stream<String> linesModifiedAndAppendedFromVariousFiles=getLines();
However, I need to feed this into an library method that accepts InputStream or Reader as a parameter.
How can I feed this Java 8 stream into an InputStream or a type of Reader?
P.S: this is not about wrapping java.util.streams.Stream around an InputStream. What I am looking for is the other way around.
We can use the ByteStreams. copy() API from transferring the bytes from InputStream to OutputStream. The ByteStreams class contains many utility methods for working with byte arrays and I/O streams. The copy() method copies all bytes from the input stream to the output stream.
Java 8 offers the possibility to create streams out of three primitive types: int, long and double. As Stream<T> is a generic interface, and there is no way to use primitives as a type parameter with generics, three new special interfaces were created: IntStream, LongStream, DoubleStream.
You can do this with PipedReader and PipedWriter.
PipedReader reader = new PipedReader();
Runnable feeder = new Runnable() {
@Override
public void run() {
try (PipedWriter writer = new PipedWriter(reader)) {
linesModifiedAndAppendedFromVariousFiles.forEachOrdered(line -> {
try {
writer.write(line);
writer.write('\n');
} catch (IOException e) {
throw new UncheckedIOException(e);
}
});
} catch (IOException e) {
throw new RuntimeException(e);
}
}
};
new Thread(feeder).start();
someLibraryMethod.consumeReader(reader);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With