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.
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);