Created
September 28, 2022 16:03
-
-
Save chochos/be7f3b17d276fd067b7124c3133ce588 to your computer and use it in GitHub Desktop.
Piped streams
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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