Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to obtain Inputstream from Java 8 Streams?

Tags:

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.

like image 828
selman Avatar asked Apr 16 '19 13:04

selman


People also ask

How do I get InputStream from OutputStream?

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.

Does java 8 support streams?

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.


1 Answers

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);
like image 131
VGR Avatar answered Oct 15 '22 20:10

VGR