Skip to content

Instantly share code, notes, and snippets.

@chochos
Created September 28, 2022 16:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chochos/be7f3b17d276fd067b7124c3133ce588 to your computer and use it in GitHub Desktop.
Save chochos/be7f3b17d276fd067b7124c3133ce588 to your computer and use it in GitHub Desktop.
Piped streams
import java.io.*;
public class Example {
private InputStream reportProducer(int lines) throws IOException {
var pin = new PipedInputStream();
var pout = new PipedOutputStream(pin);
var out = new PrintStream(pout);
Runnable generator = () -> {
for (int i = 0; i < lines; i++) {
out.println("Generating line " + i + "...");
}
out.println("Done.");
out.close();
};
new Thread(generator, "writer").start();
return pin;
}
private void writeReport(int lines) throws IOException {
String line;
try (var file = new PrintStream(new FileOutputStream("/tmp/test.txt"));
var ins = reportProducer(lines);
var reader = new BufferedReader(new InputStreamReader(ins))) {
while ((line = reader.readLine()) != null) {
file.println(line);
}
}
}
public static void main(String... args) throws IOException {
new Example().writeReport(10_000);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment